Get instance of child class

1

I have a class:

class Children extends Database

So, Children is the child class and Database the parent class, in the parent class I have the attribute:

protected $object = null;

The value of it should be the instance of the child class, currently to set this attribute I am using:

// Construtor da classe Children
public function __construct($id = null, $daddy  = null, $people = null)
{
    $this->id = $id;
    $this->daddy = $daddy ;
    $this->people = $people;
    $this->object = $this;
}

But straightforward I forget to put the line $this->object = $this; in the constructor, and this affects the operation.

If I put $this->object = $this; in the constructor of the Database class it will not work because it will store the Database instance in the attribute, not the instance of the Children class.

Is there a way in the parent class constructor to set this attribute for your child?

For when I give a new Children() the attribute object of class Database It is already worth this instance, making it necessary to have $this->object = $this; in the constructor of the child class ( Children ).

When doing new Children() the goal would be:

// Construtor da classe Database
public function __construct()
{
    $this->object = instancia criada de Children
}
    
asked by anonymous 06.07.2016 / 20:16

1 answer

4

There is no way, the daughter should always refer to the mother and not the other way around. It has to be done by hand. What it could do is the parent class constructor accept a parameter that receives the instance and stores it in the variable. But the mother builder's call will be needed.

I wonder, what if DataBase does not have a daughter?

In fact this makes little or no sense. Nor will I enter into the merit of a class which is not to be a Database to inherit from it, it may be only a bad example. But an object having a property whose value is the very instance that carries it is at the least queer. I can not say much because I do not know the general context, but this seems wrong.

    
06.07.2016 / 20:48