PHP类属性引用对象

时间:2013-12-15 14:41:42

标签: php oop

class Hello {
    public function hi() {
        echo "Hello, hi!\n";
    }
}

class ParentClass {
    public $obj;
    public function __construct() {
       $this->obj = new Hello;
    }
}

class Test extends ParentClass {
     public function __construct() { 
        $this->obj->hi();
     }
}

$temp = new Test;

我得到的错误信息是“在非对象上调用成员函数hi()”。 $ obj应该引用类“Hello”的实例,但显然不是 - 我做错了什么?

2 个答案:

答案 0 :(得分:2)

您在__construct()类中定义Test但未调用父构造函数。如果要执行父构造函数,则需要显式指定。在ParentClass类构造函数中添加对Test构造函数的调用。

class Test extends ParentClass {
     public function __construct() { 
        parent::__construct();
        $this->obj->hi();
     }
}

同样@Tasos Bitsios在评论中指出,您还需要更新ParentClass构造函数,如下所示:

class ParentClass {
    public $obj;
    public function __construct() {
       $this->obj = new Hello; // Use $this->obj and not just $obj.
    }
}

答案 1 :(得分:0)

您需要调用父构造函数:

class Test extends ParentClass {
    public function __construct() { 
        parent::__construct();
        $this->obj->hi();
    }
}
相关问题