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"的实例,但显然不是 - 我做错了什么?
您在Test
类中定义__construct()
,但不调用父构造函数。 如果希望执行父构造函数,则需要显式指定。 在类构造函数中添加对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.
}
}
你需要调用父构造函数:
class Test extends ParentClass {
public function __construct() {
parent::__construct();
$this->obj->hi();
}
}