問題是您正在創建一個未設置變量的新實例。該屬性綁定到一個特定的實例,所以你創建的父母的一個實例,然後從父母的另一個孩子的實例,其中包括所有的東西創建一個新的父母將包含,其中包括$_parent_property
。當您讀取孩子的值時,您正在讀取新創建的父代的值,而不是您之前創建的值。
實際上,你這樣做:
A = new TheParent()
A->_parent_property = 'test'
Calls:
B = new TheChild(), underneath the covers, this does new TheParent()
Print B->_parent_property (which was uninitialized)
考慮將產生你預期的結果這個類似的例子:
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
創建的實例,設置基礎實例變量。
感謝您的迴應,馬克。我剛剛更新了我的示例,以顯示在調用父方法時傳遞父屬性的值。基於你的回答,我想如果不先將它傳遞給子類,那麼不可能在屬性中保留原始參數值? –
@Calvin:你的關係是向後的,'TheChild'從'TheParent'繼承,如果你想'TheChild'擴展'TheParent',你應該把setter方法暴露給'TheChild',或者移除繼承關係並且傳遞一個實例'TheParent'到'TheChild'(或者你需要的變量) –
它們被稱爲靜態變量。爲什麼'TheParent'實例化TheChild? –