我有一个受保护的变量Father
类中,该变量的内容将发生变化Father
类,但我需要在子类中使用这个变量,即:
class Father {
protected $body;
function __construct(){
$this->body = 'test';
}
}
class Child extends Father{
function __construct(){
echo $this->body;
}
}
$c = new Father();
$d = new Child();
为什么变量body
空着来?如果我将其声明为静态,它就可以工作,如果我想在子类中访问和修改这些变量,是否应该将所有变量声明为静态?
您必须调用父构造函数。
class Father {
protected $body;
function __construct(){
$this->body = 'test';
}
}
class Child extends Father {
function __construct(){
parent::__construct();
echo $this->body;
}
}
$c = new Father();
$d = new Child();
参考:http://php.net/manual/en/language.oop5.decon.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)