Search code examples
phpoopcall

Calling a child object in the parent object


I want to know if I can create a child object in a parent object an use it...

  • I mean is it posible?
  • Is it a good idea?
  • What do I have to care if I do so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}

Solution

  • This seems to be like a bad idea IMHO - it's going to require high maintenance and you are creating some tight couplings between classes.

    i would recommend creating an abstract function in the parent that each of the children will implement with it's own logic.

    [EDIT] since you are trying to iterate over all child objects i would recommend to create a base class that handles all the logic that needs to be implemented to all children, and override it in each of the child classes that need additional logic, and call the parent function inside it.