我的印象是子类继承其父类的属性。然而,以下是类 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();
关于php - 在PHP中,我们如何获取父类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854412/