php调用父函数使父函数无法加载自己的变量
我有一个如下所示的处理程序类:php调用父函数使父函数无法加载自己的变量,php,class,parent,parent-child,Php,Class,Parent,Parent Child,我有一个如下所示的处理程序类: 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
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
}
}
工作流程:
- 从my index.php调用处理程序,并调用_构造
- 处理程序需要创建$group
- 处理程序创建子类
- 子类调用处理程序函数
- 当我尝试在函数中返回$group时,它尝试从子级而不是从处理程序中获取$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();
}
}
如果没有覆盖扩展类中的_构造方法,则会自动调用父_构造,但由于在扩展类中重写了它,您必须告诉它在扩展类中调用父级的u构造‘u构造。或者他可能希望
public$group
是静态的,而不是实际上有两个不同的对象:p@Basti不管怎样,他都必须做上述的事情,既然他没有提到你在说什么,我不知道你为什么要提起。如果我这样做,父母会再次拜访孩子,而且会有无穷无尽的麻烦loop@Basti如果我将它设为静态,它会显示Notice:Undefined属性:ChildClass::$groupI将它作为答案的扩展。没有造成伤害。