php - Call method recursively through class hierarchy -


i want call recursively parent methods :

<?php class generation1 {     public function whoami() {         echo get_class($this).php_eol;     }     public function awesome() { // stop recursion         $this->whoami();     } }  class generation2 extends generation1 {     public function awesome() {         $this->whoami();         parent::awesome();     } }  class generation3 extends generation2 {} class generation4 extends generation3 {}  $gen = new generation4(); $gen->awesome(); 

the output :

generation4

generation4

i have :

generation4

generation3

generation2

generation1

the __class__ magic constant not interpreted being whatever concrete class instance is, instead evaluates class name constant contained in.

if want concrete class name (rather base class name), try using get_class() instead.

<?php   class {     public function test1()     {         echo __class__ . "\n";     }      public function test2()     {         echo get_class($this) . "\n";     } }  class b extends {}  $b = new b;  $b->test1(); $b->test2(); 

output:

a

b

update

in particular situation, there two awesome methods; 1 defined on generation2 , 1 defined on generation1. generation3 , generation4 rely on ancestor's definitions, , not called inside of context (this why see two outputs, there's 2 methods called).

you around defining awesome method @ every level have written. trouble $this->whoami() line. $this in each of contexts referring concrete instance of generation4 object, @ generation2 level calling $this->whoami() inside of awesome method cause method on generation4 called of awesome methods.

you can around limitation, too, changing $this self. final solution able come this:

class gen1 {     public function whoami()     {         echo __class__ . php_eol;     }     public function awesome()     {         self::whoami();     } }  class gen2 extends gen1 {     public function whoami()     {         echo __class__ . php_eol;     }     public function awesome()     {         self::whoami();         parent::awesome();     } } class gen3 extends gen2 {     public function whoami()     {         echo __class__ . php_eol;     }     public function awesome()     {         self::whoami();         parent::awesome();     } } class gen4 extends gen3 {     public function whoami()     {         echo __class__ . php_eol;     }     public function awesome()     {         self::whoami();         parent::awesome();     } }  $gen4 = new gen4; $gen4->awesome(); 

which gives output of:

gen4

gen3

gen2

gen1

you may able around of these limitations if have php 5.5 installed (i on 5.4 locally right now, can't test this), see this answer other possibilities.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -