1
我喜歡this answer中提出的想法,允許在PHP中擁有類似多個構造函數的東西。我的代碼是類似於:self ::引用父類的靜態方法中的派生類
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*
方法),這很愚蠢。
如何幫助$bb
成爲B
,即使在A
上下文中調用該方法?
您正在尋找[Late Static Bindings](http://stackoverflow.com/q/1912902/1233508)。 – DCoder
也許你想'靜態'而不是'自己'? – bishop
靜態或父母, – ArtisticPhoenix