我有一个如下所示的 Handler 类:
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
Handler 创建子类
子类调用Handler函数
当我尝试在函数中返回 $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 方法,那么父级 __construct 会自动被调用,但由于您在扩展类中覆盖了它,因此您必须告诉它调用父级的 __construct 在您的扩展类的 __construct 中。
关于php 调用父函数使父函数无法加载自己的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9863627/