tags:

views:

173

answers:

2

Hi, I've been using OOP in PHP for a while now, but for some reason am having a total brain meltdown and can't work out what's going wrong here!

I have a much more complex class, but wrote a simpler one to test it, and even this isn't working...

Can anyone tell me what I'm doing wrong?

class test
{
    public $testvar;

    function __construct()
    {
       $this->testvar = 1;
    }
}

class test2 extends test
{
    function __construct()
    {
        echo $this->testvar;
    }
}

$test = new test;
$test2 = new test2;

All I'm trying to do is pass a variable from the parent class to the child class! I swear in the past I've just used $this->varName to get $varName in the extension??

Thanks!

+8  A: 

Hi,

You have to call the constructor of the parent class from the constructor of the child class.

Which means, in your case, that your test2 class will then become :

class test2 extends test
{
    function __construct()
    {
        parent::__construct();
        echo $this->testvar;
    }
}

For more informations, you can take a look at the page Constructors and Destructors of the manual, which states, about your question :

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.


You can use $this->varName : this is not a problem ; consider this code :

class test {
    public $testvar = 2;
    function __construct() {
       $this->testvar = 1;
    }
}
class test2 extends test {
    function __construct() {
        var_dump($this->testvar);
    }
}
$test2 = new test2;

The output is :

int 2

Which is the "default" value of $testvar.

This means the problem is not that you cannot access that property : the problem, here, is only that the constructor of the parent class has not been called.

Pascal MARTIN
+1 for extra detail. :)
Amber
Awesome! That worked! Thanks!
Matt
@Matt : you're welcome :-) ;; @Dav : thanks !
Pascal MARTIN
+2  A: 

Your test2 class should call

parent::__construct()

in its constructor.

Amber
Thanks! I wish I could add this as the accepted answer as well!
Matt