[英]In PHP, how do we get parent class variables?
我的印象是子類繼承了其父級的屬性。 但是,以下內容在類B中為null。有人可以告訴我如何從父類訪問屬性嗎?
$aClass = new A();
$aClass->init();
class A {
function init()
{
$this->something = 'thing';
echo $this->something; // thing
$bClass = new B();
$bClass->init();
}
}
class B extends A {
function init()
{
echo $this->something; // null - why isn't it "thing"?
}
}
您的代碼中有幾個錯誤。 我已經糾正了。 下面的腳本應該可以正常工作。 我希望代碼注釋對您有所幫助:
class A {
// even if it is not required you should declare class members
protected $something;
function init()
{
$this->something = 'thing';
echo 'A::init(): ' . $this->something; // thing
}
}
// B extends A, not A extends B
class B extends A {
function init()
{
// call parent method to initialize $something
// otherwise init() would just being overwritten
parent::init();
echo 'B::init() ' . $this->something; // "thing"
}
}
// use class after(!) definition
$aClass = new B(); // initialize an instance of B (not A)
$aClass->init();
您定義的第二個類應該是class B extends A
,而不是class A extends B
我們使用以下語法在PHP中訪問父類成員:
parent::$variableName
要么
parent::methodName(arg, list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.