从父构造函数在 PHP 中设置的子类访问父类属性


Access parent class properties from child class that have been set by parent constructor in PHP

好吧,我遇到了一点问题。场景如下:我需要能够获取 test2 的构造函数才能访问由 main_class 构造函数设置的 main_class 内部的类属性测试。我不确定如何让它工作,我需要系统像这样工作。现在,如果我在代码中设置类变量,这将起作用,就像在类定义中var test = "hello";这样,但当然在这种情况下,main_class::test 是由它的构造函数设置的,而不是"var",所以它不起作用。

这是我的代码的高度简化版本:

索引.php:

<?php
class main_class
{
    private $test2;
    public function __construct()
    {
        $this->test2 = array();
        include("./test1.php");
        $var_name = "test";
        $this->$var_name = new test1();
    }
    protected function do_include()
    {
        include("./test2.php");
        $this->test2["test2"] = new test2();
    }
}
$test = new main_class();
?>

测试1.php:

class test1 extends main_class
{
    public function __construct()
    {
        $this->do_include();
    }
}
?>

测试2.php:

class test2 extends test1
{
    public function __construct()
    {
        print_r($this->test);
    }
}
?>

使用此代码,我收到此错误: 注意:未定义的属性:test2::$test

提前感谢...

我怀疑部分问题可能是您没有在 test2 类中调用父构造函数:

class test2 extends test1
{
    public function __construct()
    {
        parent::__construct();
        print_r($this->test);
    }
}

如果省略了该行,则 test2 构造函数将完全覆盖 test1 构造函数,并且永远不会调用 $this->do_include()

另外,请记住,当您调用 $this->test2["test2"] = new test2(); 时,您正在创建此类的新实例,该实例与当前实例无关。

澄清一下,以下是事件的顺序:

$test = new main_class(); // calls the constructor of main_class:

public function __construct()
{
    $this->test2 = array();
    include("./test1.php");
    $var_name = "test";
    $this->$var_name = new test1();
}

然后:

$this->$var_name = new test1(); // calls the constructor of test1:

public function __construct()
{
    $this->do_include();
}

。从main_class调用 do_include():

protected function do_include()
{
    include("./test2.php");
    $this->test2["test2"] = new test2();
}

然后:

$this->test2["test2"] = new test2(); // calls the constructor of test2:

public function __construct()
{
    print_r($this->test);
}

这将创建一个对象,而您在其构造函数中所做的只是打印一个尚不存在的变量 ($test)。因为你没有做任何事情来创建它。