从父类返回子类

use*_*437 5 php oop design-patterns class

希望有人可以帮助我。

我想要一个包含两个子类之间通用功能的“基/父”类,但我也希望基/父的构造函数决定使用哪个子类 - 所以我可以简单地创建一个 ParentClass 的实例,并使用父类->方法();但它实际上在做的是决定使用哪个孩子并创建该孩子的实例。

我认为这样做的方法是返回 new ChildClass(); 在构造函数中,然后 get_class() 在 'base/shared' 方法中返回 ParentClass。

一个小例子(我的班级比这更复杂,所以我不只是直接调用子班级可能看起来很奇怪):

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要:

$ParentClass = new ParentClass('a');
echo $ParentClass->sharedMethod();
Run Code Online (Sandbox Code Playgroud)

并期望输出为“测试”。

我也打算让子类拥有自己的方法,我可以使用 $ParentClass->nonShareMethod() 来调用它们。因此 ParentClass 既充当“代理”又充当“基础”。

Sha*_*ran 1

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

  • 有什么办法可以实现我想要的吗?我想要一个具有子级通用功能的基类,可以覆盖方法。但我想要一个单一的访问点,这样就可以决定我需要哪个类,并将创建该类的一个实例供我使用。 (2认同)