Phil Jackson
Phil Jackson

Reputation: 10288

php classes extend

Hi I have a question regarding $this.

class foo {

    function __construct(){

       $this->foo = 'bar';

    }

}

class bar extends foo {

    function __construct() {

        $this->bar = $this->foo;

    }

}

would

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

result in bar??

I only ask due to I thought it would but apart of my script does not seem to result in what i thought.

Upvotes: 6

Views: 4158

Answers (3)

Mark Baker
Mark Baker

Reputation: 212402

You don't create an instance of both foo and bar. Create a single instance of bar.

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

and as other answers have pointed out, call parent::__construct() within your bar constructor

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300825

PHP is a little odd in that a parent constructor is not automatically called if you define a child constructor - you must call it yourself. Thus, to get the behaviour you intend, do this

class bar extends foo {

    function __construct() {

         parent::__construct();
         $this->bar = $this->foo;

    }

}

Upvotes: 5

Vilx-
Vilx-

Reputation: 106902

To quote the PHP manual:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

This means that in your example when the constructor of bar runs, it doesn't run the constructor of foo, so $this->foo is still undefined.

Upvotes: 9

Related Questions