Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return child class from parent

Hoping someone can help me.

I want a 'base/parent' class that holds the common functionality between two child classes, but I also want the constructor of the base/parent to decide which child class to use - so I can simply create an instance of ParentClass, and use ParentClass->method(); but what it is actually doing is deciding which child to use and creating an instance of that child.

I thought the way to do this would be to return new ChildClass(); in the constructor, but then get_class() returns the ParentClass in the 'base/shared' methods.

A little example (My class is more complex than this, so it may look odd that I for example am not just calling the child class directly):

class ParentClass {
  private $aVariable;
  public function __construct( $aVariable ) {
    $this->aVariable = $aVariable;
    if ($this->aVariable == 'a') {
      return new ChildClassA();
    else {
      return new ChildClassB();
    }
  }

  public function sharedMethod() {
    echo $this->childClassVariable;
  }
}

class ChildClassA extends ParentClass {
    protected $childClassVariable;
    function __construct() {
        $this->childClassVariable = 'Test';
    }
}

class ChildClassB extends ParentClass {
    protected $childClassVariable;
    function __construct() {
        $this->childClassVariable = 'Test2';
    }
}

I want to:

$ParentClass = new ParentClass('a');
echo $ParentClass->sharedMethod();

And expect the output to be 'Test'.

It also also my intention that a child class would have their own methods and I can use $ParentClass->nonShareMethod() to call them. So ParentClass is both acting as a 'proxy' and as a 'base'.

like image 935
user3364437 Avatar asked Nov 23 '22 02:11

user3364437


1 Answers

You cannot execute the methods of the child class from the parent class !

like image 128
Shankar Narayana Damodaran Avatar answered Jan 21 '23 11:01

Shankar Narayana Damodaran