<?php
class Super {
public $my;
public function __construct ( $someArg ) {
if ( class_exists('Sub') ) { // or some other condition
return new Sub( $someArg );
}
$this->my = $someArg;
}
}
class Sub extends Super {}
?>
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为new Super()它将是一个"空" Super对象(所有成员都是NULL).(PHP不允许分配$this,因此$this = new Sub()也不起作用).
我知道正确的模式将是这里的工厂.但这需要对代码进行大量更改,所以我想知道是否可以这样做.既然Sub是-a Super,我不明白为什么不应该从OOP的角度来限制它.
你在这里弄错了.构造函数没有返回值,你不能从构造函数返回一个实例 - 一旦调用了构造函数,类已经解决,你就不能再改变它了.
你想要做的是为此实现工厂模式:
<?php
class Super {
public $my;
public function __construct ( $someArg ) {
$this->my = $someArg;
}
public static function factory ($somearg) {
if ( class_exists('Sub') && $somearg["foo"] == "bar") { // or some other condition
return new Sub( $someArg );
}
else {
return new Super($someArg);
}
}
}
class Sub extends Super {}
$mynewsuborsuper = Super::factory($myargs);
?>
Run Code Online (Sandbox Code Playgroud)