我有一个处理程序类,如下所示:
class Handler{
public $group;
public function __construct(){
$this->group = $this->database->mysql_fetch_data("blabla query");
//if i print_r($this->group) here it gives proper result
new ChildClass();
}
public function userGroup(){
print_r($this->group); //this is empty
return $this->group;
}
}
class ChildClass extends Handler{
public function __construct(){
$this->userGroup();
//i tried this too
parent::userGroup();
//userGroup from parent always returns empty
}
}
工作流程:
处理程序是从我的index.php调用的,__construct被称为
处理程序需要创建$group
处理程序创建子类
子类调用处理程序函数
当我试图在函数中返回$group时,它试图从Child而不是Handler 获得$this->group
每当我试图问父类一些事情时,我只能访问父函数,然后在函数内部,父类找不到它自己的任何变量
编辑:
我认为使用"extends"在调用父函数时会很有用,但似乎只将$this传递给子函数会更容易。
您从未调用过父构造函数,因此组对象从未初始化。你会想做这样的事情。
class Handler{
public $group;
public function __construct(){
$this->group = $this->database->mysql_fetch_data("blabla query");
//if i print_r($this->group) here it gives proper result
new ChildClass();
}
public function userGroup(){
print_r($this->group); //this is empty
return $this->group;
}
}
class ChildClass extends Handler{
public function __construct(){
parent::__construct();
$this->userGroup();
}
}
如果没有覆盖扩展类中的__construct方法,那么父__construction将自动被调用,但由于您在扩展类中覆盖了它,您必须告诉它在扩展类的__constrain中调用父__construction。