访问作为父类

时间:2016-08-08 17:24:16

标签: php oop constructor parent-child protected

我正在尝试从子类访问对象的函数,其中对象是父对象的受保护变量。

我不完全确定最好的解决方法......任何帮助或指示都会受到赞赏。

以下是我现在设置的方式,但它不起作用。它给出了以下错误:

  

捕获致命错误:参数1传递给App \ Parent :: __ construct()   必须是App \ Object的一个实例,没有给出,调用   第25行的Controller.php,第12行的Parent.php中定义

因此,当我理解错误时,我需要以某种方式将Parent类的实例传递给Child类。但这似乎是一种反模式,因为它扩展了Parent类。我必须遗漏一些基本的东西。

Parent.php

class Parent
{
    protected $object;

    public function __construct(Object $object) // line 12
    {
        $this->object = $object;
    }

}

Child.php

class Child extends Parent
{
    public function doStuff()
    {
        return parent::$object->objectFunction());
    }

}

Controller.php这样

...

namespaces etc

...

public function control()
{
    $parent = new Parent(new Object($variable));

    $child = new Child(); // line 25
    $child->doStuff();
}

1 个答案:

答案 0 :(得分:1)

不要实例化一个单独的父类,它将被实例化为实例化子类的一部分。

还将对象传递给子实例化并创建__construct()方法并将参数传递给它。

class Child extends Parent
{
    public __construct($var)
    {
        parent::__construct($var);
    }

    public function doStuff()
    {
        return parent::$object->objectFunction());
    }

}

Controller.php这样

public function control()
{
    //$parent = new Parent(new Object($variable));

    $child = new Child(new Object($variable)); // line 25
    $child->doStuff();
}