我喜欢这个答案中提出的允许在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
常数是类A
,因此变量$aa
和$bb
都属于类A
,而我希望$bb
是类B
。
如果我使用$this
特殊变量,当然这将是类B
,即使在A
范围内,如果我从B
调用任何父方法。
我知道我可以复制整个create()
方法(也许Traits确实有帮助?),但我也必须复制所有的"构造函数"(所有create*
方法),这太愚蠢了。
即使在A
上下文中调用该方法,我如何帮助$bb
变为B
?
您想要使用static
,它表示在其中调用方法的类。(self
表示定义方法的类。)
static public function create(){
$instance = new static();
//... some important code
return $instance;
}
请参阅有关延迟静态绑定的文档。
您需要PHP 5.3+才能使用此功能。