1

Suppose we have three classes like these:

class A { public function name(){ echo get_called_class(); } } class B extends A { public function name(){ parent::name(); } } class C extends B { public function name(){ parent::name(); } } $c = new C(); $c->name(); //Result is C 

If you run this code, the result will be "C". However, I need the name of first child class, "B". Is there any Idea? Thanks.

1 Answer 1

1

This was a fun one, thanks for the interesting question!

The following code will give you the ability to obtain the first child of the root parent from any child class.

class A { public function name(){ return 'Undefined'; } protected function identify_first_child() { $root = self::class; $node = static::class; $parent = get_parent_class($node); while ($parent !== $root) { $node = $parent; $parent = get_parent_class($parent); } return $node; } } class B extends A { public function name(){ return $this->identify_first_child(); } } class C extends B { public function name(){ return $this->identify_first_child(); } } class D extends A { public function name(){ return $this->identify_first_child(); } } class E extends D { public function name(){ return $this->identify_first_child(); } } class F extends A { public function name(){ return $this->identify_first_child(); } } $a = new A(); echo $a->name() . '<br>'; $b = new B(); echo $b->name() . '<br>'; $c = new C(); echo $c->name() . '<br>'; $d = new D(); echo $d->name() . '<br>'; $e = new E(); echo $e->name() . '<br>'; $f = new F(); echo $f->name() . '<br>'; 

This will output the following:

Undefined B B D D F 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @ArchCodeMonkey! It was interesting solution and works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.