希望有人能帮助我。
我想要一个“基础/父级”类来保存两个子类之间的共同功能,但我也希望父级的构造函数决定使用哪个子类 - 这样我就可以简单地创建ParentClass实例,并使用ParentClass->method();但实际上它正在决定使用哪个子类并创建该子类的实例。
我认为做到这一点的方法是在构造函数中返回new ChildClass();,但是get_class()在“基础/共享”方法中返回ParentClass。
以下是一个小例子(我的类比这更复杂,因此看起来可能有些奇怪,例如我不直接调用子类):
我想要一个“基础/父级”类来保存两个子类之间的共同功能,但我也希望父级的构造函数决定使用哪个子类 - 这样我就可以简单地创建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既充当“代理”,又充当“基类”。
__construct()
中做什么(除非引发异常或终止脚本),它都将返回_所属类的实例_(更准确地说,不是_返回_,而是在通过new
调用时实例化)。因此,您的条件返回没有意义。 - Alma Doextends ParentClass
,而非extends ParentClass()
,另外,if ($this->aVariable == 'a') {
后面缺少一个右括号。 - Rohit Awasthi