从父类返回子类

5
希望有人能帮助我。
我想要一个“基础/父级”类来保存两个子类之间的共同功能,但我也希望父级的构造函数决定使用哪个子类 - 这样我就可以简单地创建ParentClass实例,并使用ParentClass->method();但实际上它正在决定使用哪个子类并创建该子类的实例。
我认为做到这一点的方法是在构造函数中返回new ChildClass();,但是get_class()在“基础/共享”方法中返回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';
    }
}

我希望:

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

期望的输出结果是'Test'。

我的意图是,子类应该有自己的方法,我可以使用$ParentClass->nonShareMethod()来调用它们。因此,ParentClass既充当“代理”,又充当“基类”。


2
无论在__construct()中做什么(除非引发异常或终止脚本),它都将返回_所属类的实例_(更准确地说,不是_返回_,而是在通过new调用时实例化)。因此,您的条件返回没有意义。 - Alma Do
您的代码中有拼写错误。应该写成extends ParentClass,而非 extends ParentClass(),另外,if ($this->aVariable == 'a') { 后面缺少一个右括号。 - Rohit Awasthi
4
你可能会对 http://en.wikipedia.org/wiki/Factory_method_pattern 感兴趣。该页面介绍了工厂方法模式的相关信息。 - VolkerK
抱歉拼写错误,这基本上是使用我的代码作为参考而不是实际工作示例编写的伪代码。对此感到抱歉。 - user3364437
谢谢 - 我认为工厂方法模式是我需要的。 - user3364437
1个回答

1

你不能从父类中执行子类的方法!


2
有没有办法实现我想要的功能?我想要一个具有通用功能的基类,子类可以覆盖方法。但是我想要一个单一的访问点,所以需要一个能够决定我需要哪个类并为我创建该类实例以供使用的东西。 - user3364437

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接