简体   繁体   中英

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'.

您不能从parent类执行child类的方法!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM