我有一个看起来像这样的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调用Handler,调用__construct
处理程序需要创建$ group
处理程序创建子类
子类调用Handler函数
当我尝试在函数中返回$ group时它试图从Child而不是Handler获取$ this->组
每当我尝试向父母询问我只能访问父函数时,在函数内部,父类无法找到任何自己的变量
编辑:
我认为使用'extends'会在调用父函数时很有用,但似乎只是将$ this传递给孩子会更容易。
答案 0 :(得分:2)
您从未调用过父构造函数,因此永远不会初始化组对象。你会想做这样的事情。
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。
中