John Smith
John Smith

Reputation: 6197

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?

Upvotes: 0

Views: 116

Answers (1)

JJJ
JJJ

Reputation: 33163

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.

Upvotes: 2

Related Questions