php 调用父函数使父函数无法加载自己的变量

标签 php class parent parent-child

我有一个如下所示的 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/

相关文章:

Java多态行为

javascript - 阻止对父级的相同域 iframe 访问

php - 有什么方法可以访问所有标记有带循环的类的 div 吗?

php - CakePHP - 如何更新多条记录

php - 功能性重定向的 HTTP 状态

java - 将 Java 对象/字符串转换为实际类

c++ - 具有设置参数的静态成员函数需要访问非静态数据成员

jQuery 选择父级

JavaFX - 如何让 VBox child 与 VBox parent 一起成长

php - 在 PHP 中创建 PDF 页面