2015-06-30 114 views
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,而我希望$bbB類別。

如果我使用$this特殊的變量,這當然是B類,甚至在A範圍,如果我叫任何父類的方法從B。我知道我可以複製整個create()方法(也許Traits幫助?),但我也必須複製所有「構造函數」(全部爲create*方法),這很愚蠢。

如何幫助$bb成爲B,即使在A上下文中調用該方法?

+1

您正在尋找[Late Static Bindings](http://stackoverflow.com/q/1912902/1233508)。 – DCoder

+1

也許你想'靜態'而不是'自己'? – bishop

+0

靜態或父母, – ArtisticPhoenix

回答

2

您想要使用static,它代表方法爲的類別,稱爲。 (self表示類,其中所述方法是定義。)

static public function create(){ 
    $instance = new static(); 
    //... some important code 
    return $instance; 
} 

參考文檔上Late Static Bindings

你需要PHP 5.3+來使用它。

相關問題