【发布时间】:2011-07-30 22:11:55
【问题描述】:
我无法理解为什么我可以从我的父类访问一个属性,但它是 NULL,即使它已经由父类设置(并且没有被故意重置)。我认为这可能是因为该属性是由私有方法设置的,但是当我更改为 public 时没有区别。这是一个彻底简化的示例:
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在我原来的例子中。
我确实知道,如果我从父构造函数中设置此属性,我就可以正常访问它。我试图理解为什么由父方法设置并可由其他父方法访问的属性不能从扩展父级的子类访问。
谁能解释一下?谢谢!
【问题讨论】:
标签: php oop inheritance properties