PHP如何从构造函数返回子类 [英] How to return subclass from constructor in PHP
问题描述
<?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 {}
?>
这不起作用,因为 new Super()
将是一个空"的 Super
对象(所有成员都是 NULL
).(PHP 不允许对 $this
赋值,所以 $this = new Sub()
也不起作用).
This doesn't work, as new Super()
will be an "empty" Super
object (all members are NULL
). (PHP doesn't allow assignments to $this
, so $this = new Sub()
doesn't work either).
我知道正确的模式应该是这里的工厂.但这需要对代码进行大量更改,所以我想知道是否可以这样做.由于 Sub
是一个 Super
,我不明白为什么它不应该从 OOP 的角度受到限制.
I know the correct pattern would be a factory here. But that would require a lot of changes in the code, so I'm wondering whether it's possible to do it this way. Since Sub
is-a Super
, I don't see why it shouldn't be restricted from an OOP point of view.
推荐答案
您不能分配给 $this
并且不能从构造函数返回任何内容.
You can't assign to $this
and you cannot return anything from a constructor.
这篇关于PHP如何从构造函数返回子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!