Search code examples
phpoopobjectparent

php, I need child object from parent, how?


class Parent
{
 public function exec()
 {
  // here I need the child object!
 }
}

class Child extends Parent
{
 public function exec()
 {
  // something
  parent::exec();
 }
}

as you can see, I need the child object from the parent. How can I reach it?


Solution

  • You can pass the child as an argument:

    class ParentClass
    {
        public function exec( $child )
        {
            echo 'Parent exec';
            $child->foo();
        }
    }
    
    class Child extends ParentClass
    {
        public function exec()
        {
            parent::exec( $this );
        }
    
        public function foo() 
        {
            echo 'Child foo';
        }
    }
    

    This is rarely needed though, so there might be a better way to do what you're trying to do.