PHP classes are expanding

Hi, I have a question regarding $ this.

class foo { function __construct(){ $this->foo = 'bar'; } } class bar extends foo { function __construct() { $this->bar = $this->foo; } } 

will be

 $ob = new foo(); $ob = new bar(); echo $ob->bar; 

lead to bar ??

I only ask because I thought it would be, but apart from my script, it does not seem to lead to what I thought.

+6
php class extends
source share
3 answers

To quote the PHP manual :

Note. Parent constructors are not called implicitly if the child class defines the constructor. To start the parent constructor, you need to call parent :: __ construct () inside the child constructor.

This means that in your example, when the bar constructor is executed, it does not start the foo constructor, so $this->foo is still undefined.

+10
source share

PHP is a little strange in that the parent constructor is not called automatically, if you define a child constructor - you have to call it yourself. So in order to get the behavior you intend, do it

 class bar extends foo { function __construct() { parent::__construct(); $this->bar = $this->foo; } } 
+5
source share

You do not instantiate both foo and bar. Create one instance of the panel.

 $ob = new bar(); echo $ob->bar; 

and as other answers pointed out, call parent :: __ construct () in your bar constructor

0
source share

All Articles