Pass variable to PHP extended class

I have been using OOP in PHP for a while, but for some reason I have a general brain crisis and cannot understand what is going wrong here!

I have a much more complex class, but he wrote a simpler one to test it, and even that doesn't work ...

Can someone tell me what I am 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 am trying to do is pass a variable from the parent class to the child class! I swear in the past I used $ this-> varName to get $ varName in the extension

Thanks!

+3
source share
2 answers

You must call the constructor of the parent class from the constructor of the child class.

, test2 :

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

, :

: , . , parent::__construct() .


$this->varName: ; :

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

:

int 2

$testvar.

, , : , .

+15
source

Your class test2should call

parent::__construct()

in its constructor.

+2
source

Source: https://habr.com/ru/post/1718101/


All Articles