PHP OOP: Issues with properties and extended class -
let's have php script:
<?php class aaa { protected $var = null; public function performsomething() { $this->var = 'now have string, not more null value'; $bbb = new bbb(); $bbb->poweronyou(); } } class bbb extends aaa { public function poweronyou() { var_dump($this->var); // dump "null" , not string } } $aaa = new aaa(); $aaa->performsomething(); how can note class "var_dump" everytime null, , not string.
of course need output string.
this sandbox link: http://sandbox.onlinephpfunctions.com/code/6cd253e1945e78f114749be55ffc5f88ab44dd42
thank you
note $var instance variable, not class variable. means, every instance of class has own copy of it.
you create instance of class aaa , set $aaa's copy of $var 'now have string, not more null value'. however, inside performsomething(), create new instance of class bbb, has own copy of $var. since did not set $bbb's $var, null when output it.
have @ code , try understand it; did not have opportunity test since @ work right now, should give desired output:
<?php class aaa { protected $var = null; public function poweronyou() { var_dump($this->var); } } class bbb extends aaa { public function performsomething() { $this->var = 'now have string, not more null value'; $this->poweronyou(); } } $bbb = new bbb(); $bbb->performsomething();
Comments
Post a Comment