从子方法访问时,父方法属性设置的父类属性为空

时间:2011-07-30 22:11:55

标签: php oop inheritance properties

我无法理解为什么我可以从我的父类访问属性,但它是NULL,即使它已经由父级设置(并且没有被故意重置)。我认为这可能是因为该属性是由私有方法设置的,但是当我改为公开时​​没有区别。这是一个简单的简化示例:

class TheParent
{

    protected $_parent_property;

    function __construct()
    {}

    private function parent_method($property);
    {
        $this->_parent_property = $property;
            $call = new TheChild;
            $call->child_method();
    }
}

class TheChild extends TheParent
{ 
    function __construct()
    {
        parent::construct();
    }

    public function child_method();
    {
        echo $this->_parent_property;
            exit;
    }
}

$test = new TheParent;
$test->parent_method('test');

我通过父属new TheChild($this->_parent_property)构建子项时将父属性传递给子项来解决这个问题,但我仍然不明白为什么$ this-> _parent_property在被访问时被设置为NULL从我原来的例子中的孩子。

我知道如果我从父构造函数设置此属性,我就可以正常访问它。我试图理解为什么父类方法设置的属性,以及其他父方法可访问的属性无法从扩展父类的子类访问。

有人可以解释一下吗?谢谢!

2 个答案:

答案 0 :(得分:3)

问题是您正在创建一个未设置变量的新实例。该属性绑定到一个特定的实例,所以你要创建一个父实例,然后从父实例创建另一个子实例,其中包括创建新父项的所有内容,包括$_parent_property。当您读取子项中的值时,您正在读取新创建的父项的值,而不是您之前创建的父项的值。

实际上,你这样做:

A = new TheParent()
A->_parent_property = 'test'

呼叫: 封底下方的B = new TheChild()new TheParent()

Print B->_parent_property(未初始化)

考虑这个会产生预期结果的类似例子:

class TheParent
{

    protected $_parent_property;

    function __construct()
    {
        parent_method();
    }

    private function parent_method();
    {
        $this->_parent_property = 'test';
    }
}

class TheChild extends TheParent
{ 
    function __construct()
    {
        parent::construct();
    }

    public function child_method();
    {
        echo $this->_parent_property;
        exit;
    }
}

$child = new TheChild();
$child->child_method();

在此示例中,TheParent中的私有方法在TheChild创建的同一实例上调用,设置基础实例变量。

答案 1 :(得分:2)

您对继承的工作原理略有错误。

TheParent是一个类,TheChild是基于TheParent的类。 $test现在是TheParent的一个实例。根据班级TheChild,它不知道还有另一个班级TheParent

您创建了一个$call类型的新实例TheChild。这是另一个词,一个新的对象。它与$test无关,只是两者都与TheParent“兼容”。

TheChild$call)从其父(class)继承属性_parent_property。但是,该属性未在该实例(对象)中初始化/设置,因此它仍为NULL

相关问题