PHP中的类继承问题

sza*_*489 2 php inheritance extends properties class

嗨stackOverflow系列:),

我有一个问题,我在其他地方找到了答案.我试着解释我的问题:我有一个类,如果我从它创建一个其他类,从那个子类我无法访问父类的属性.我做错事情了?我试图将我的类变量复制到本地并尝试返回本地变量,但是不能使用以下3种方式.

这是我的例子.首先,我简单地创建一个对象:

$test = new test();
Run Code Online (Sandbox Code Playgroud)

我的两个课程如下:

class test {

    public $testvar;

    public function __construct() {
        $this->testvar = 1234568;
        echo ":) ".$this->testvar();
        $test2 = new test2();
}

    public function testvar() {
        echo "testvar() called > ";
        return $this->testvar;
    }
}
Run Code Online (Sandbox Code Playgroud)

和test2:

class test2 extends test  {

    public function __construct() {
        echo "<br>:| this-> ".$this->testvar;
        echo "<br>:| parent:: ". parent::testvar();
        echo "<br>:| "; $this->testvar();
    }

}
Run Code Online (Sandbox Code Playgroud)

有人有想法吗?谢谢

Lek*_*eyn 6

你误解了继承概念.test2在构造函数中实例化test不是继承.

test没有调用构造函数,因此testvar没有设置.$test2 = new test2();从构造函数中删除test.尝试:

class test {

    public $testvar;

    public function __construct() {
        $this->testvar = 1234568;
        echo ":) ".$this->testvar();
}

    public function testvar() {
        echo "testvar() called > ";
        return $this->testvar;
    }
}

class test2 extends test  {

    public function __construct() {
        parent::__construct();
        echo "<br>:| this-> ".$this->testvar;
        echo "<br>:| "; $this->testvar();
    }

}

$test2 = new test2();
Run Code Online (Sandbox Code Playgroud)

另请参阅关于构造函数PHP手册(以及).