[英]In PHP, how do we get parent class variables?
I was under the impression that child class inherit the properties of their parent. 我的印象是子类继承了其父级的属性。 The following, however, is output null in class B... Can someone tell me how I access properties from the parent class? 但是,以下内容在类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"?
}
}
There are several errors in your code. 您的代码中有几个错误。 I've corrected them. 我已经纠正了。 The following script should work as expected. 下面的脚本应该可以正常工作。 I hope the code comments are helpful: 我希望代码注释对您有所帮助:
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
We access parent class members in PHP using the following syntax: 我们使用以下语法在PHP中访问父类成员:
parent::$variableName
Or 要么
parent::methodName(arg, list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.