Return child class from parent

Hope someone can help me.

I need a base / parent class that contains common functionality between two child classes, but I also want the base / parent constructor to decide which child class to use - so I can just instantiate the ParentClass and use the ParentClass-> ( ); but what he actually does is decide which child to use and create an instance of that child.

I thought that this would be done to return a new ChildClass (); in the constructor, but then get_class () returns the ParentClass in the "base / shared" methods.

A small example (my class is more complex than this, so it may seem strange that, for example, I do not just call 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:

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

, "Test".

, , $ParentClass- > nonShareMethod() . , ParentClass "" "".

+4
1

child parent!

0

Source: https://habr.com/ru/post/1529391/


All Articles