Search code examples
phpoopconstructorparent-childprotected

Access a member function of an object that is a member variable of a parent class


I'm trying to access a function of an object from a child class, where the object is a protected variable of the parent.

I'm not entirely sure the best way to go about this... any help or pointers would be appreciated.

Below is how I have it setup now, but it's not working. It gives the following error:

Catchable fatal error: Argument 1 passed to App\Parent::__construct() must be an instance of App\Object, none given, called in Controller.php on line 25 and defined in Parent.php on line 12

So as I understand the error, I need to somehow pass an instance of the Parent class into the Child class. But this seems like an anti-pattern because it's extending the Parent class. I must be missing something basic.

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();
}

Solution

  • Dont instantiate a seperate parent class, it will be instantiated as part of instantiating the child class.

    Also pass the object to the child instantiation and create a __construct() method and pass the parameter on to it.

    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();
    }