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

时间:2013-09-30 17:41:34

标签: php class properties parent

好的,我有一点问题。这是场景: 我需要能够获得test2的构造函数,以便能够访问main_class中由main_class构造函数设置的类属性测试。我不确定如何让它工作,我需要系统像这样工作。现在,如果我在代码中设置类变量,这个WOULD会工作,比如类定义中的这个var test = "hello";,但当然在这种情况下,main_class :: test是由它的构造函数设置的,而不是“var” ,所以它不起作用。

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

的index.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();

?>

test1.php:     

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

?>

test2.php:     

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

?>

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

提前致谢...

1 个答案:

答案 0 :(得分:1)

我怀疑问题的一部分可能是你没有在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);
}

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