我喜欢这个答案中提出的想法,允许在 PHP 中使用多个构造函数。我的代码类似于:
class A {
protected function __construct(){
// made protected to disallow calling with $aa = new A()
// in fact, does nothing
};
static public function create(){
$instance = new self();
//... some important code
return $instance;
}
static public function createFromYetAnotherClass(YetAnotherClass $xx){
// ...
}
class B extends A {};
$aa = A::create();
$bb = B::create();
现在我想创建一个派生类B,它将使用相同的“伪构造函数”,因为它是相同的代码。但是,在这种情况下,当我不对create()方法进行编码时,self常量是 class A,所以变量$aa和$bb都是 class A,而我希望$bb是 class B。
如果我使用$this特殊变量,这当然是 class B,即使在A范围内,如果我从B.
我知道我可以复制整个create()方法(也许 Traits 有帮助?),但我还必须复制所有“构造函数”(所有create*方法),这很愚蠢。
即使在上下文中调用该方法,我如何才能帮助$bb成为?BA