【发布时间】:2014-04-01 08:01:39
【问题描述】:
希望有人可以帮助我。
我想要一个“基/父”类,它包含两个子类之间的通用功能,但我也希望基/父的构造函数决定使用哪个子类 - 所以我可以简单地创建 ParentClass 的实例, 并使用 ParentClass->method();但它实际上在做的是决定使用哪个孩子并创建该孩子的实例。
我认为这样做的方法是返回 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';
}
}
我想:
$ParentClass = new ParentClass('a');
echo $ParentClass->sharedMethod();
并期望输出为“测试”。
我还打算让子类有自己的方法,我可以使用 $ParentClass->nonShareMethod() 来调用它们。因此,ParentClass 既充当“代理”又充当“基地”。
【问题讨论】:
-
无论您将在
__construct()中做什么(除非引发异常或终止脚本) - 它都会返回 它所属的类的实例(更多准确的,不是 return - 而是 instantiate 在上下文中,例如通过new调用)。所以你的条件回报没有意义 -
您的代码存在拼写错误。 extends ParentClass() 改写 ParentClass,并且 if ($this->aVariable == 'a') { 缺少中括号。
-
抱歉拼写错误,它是使用我的代码作为参考而不是工作示例编写的几乎是伪代码。对此感到抱歉。
-
谢谢 - 我认为工厂方法模式是我需要的。
标签: php class oop design-patterns