php classes extend
Asked Answered
P

3

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.

Polychasium answered 7/11, 2010 at 15:29 Comment(0)
G
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.

Gangplank answered 7/11, 2010 at 15:33 Comment(0)
K
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;

    }

}
Karelian answered 7/11, 2010 at 15:33 Comment(3)
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)...Tace
So $this has no meaning onece the extended class is called? I thought $this would carry its objects with it.Polychasium
No, $this continues to reference the current instanceKarelian
P
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

Proposal answered 7/11, 2010 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.