我正在设置一个父类属性,如下所示:
class Parent {
protected $object;
protected $childObject;
function __construct() {
$this->object = new Object();
//I can access the objects methods here
$this->childObject = new Child();
}
}
但是当我尝试在子中访问时,当我尝试访问该方法时,我得到CCD_。
class Child extends Parent {
function __construct() {
$this->object->method();
//But here I just get NULL
}
}
class Object extends Parent {
public function method() {
//do stuff
}
}
并且父类是在声明所有类之后启动的。
您还必须调用父构造函数才能将对象分配给属性,如下所示:
class Child extends Parent {
function __construct() {
parent::__construct();
//^^^^^^^^^^^^^^^^^^^^^^ See here I call the constructor of the parent
$this->object->method();
}
}
有关构造函数和析构函数的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.decon.php