6

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.

0

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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;

    }

}

3 Comments

A little odd, but VERY flexible since you can easily not overload at all (only call the parent), partially overload the constructor (calling it from within the new one) or fully overload it (not calling it at all). So while it's odd in comparison to other languages, that doesn't mean it's odd that it does this (it can be seen as a huge benefit)...
So $this has no meaning onece the extended class is called? I thought $this would carry its objects with it.
No, $this continues to reference the current instance
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.