php Child Class确实继承了空对象

时间:2015-02-27 18:41:18

标签: php

我正在设置像这样的父类属性:

class Parent {
    protected $object;
    protected $childObject;
    function __construct() {
        $this->object = new Object();
        //I can access the objects methods here
        $this->childObject = new Child();
    }
}

但当我尝试访问该孩子时,当我尝试访问该方法时,我得到all to a member function method() on a non-object

class Child extends Parent {

    function __construct() {
        $this->object->method();
        //But here I just get NULL
    }
}

class Object extends Parent {
     public function method() {
        //do stuff
     }
}

在声明所有类之后启动父类。

1 个答案:

答案 0 :(得分:0)

您还必须调用父构造函数才能将对象分配给属性,如下所示:

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