简体   繁体   中英

Pass variable to extended PHP class

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!

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.

Your test2 class should call

parent::__construct()

in its constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM