我正在一個web應用程序框架中工作,其中的一部分包含許多服務,所有服務都以單例實現。它們都繼承Service類,其中單行爲實現的,看起來像這樣:現在在PHP中擴展單例
class Service {
protected static $instance;
public function Service() {
if (isset(self::$instance)) {
throw new Exception('Please use Service::getInstance.');
}
}
public static function &getInstance() {
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
,如果我有實現這樣的叫的FileService類:
class FileService extends Service {
// Lots of neat stuff in here
}
...打電話FileService :: getInstance()不會像我希望的那樣產生FileService實例,而是產生一個Service實例。我假設這裏的問題是Service構造函數中使用的「self」關鍵字。
有沒有其他方法可以實現我想要的?單例代碼只有幾行,但我仍然希望儘可能避免任何代碼冗餘。
供參考:該代碼使用['get_called_class'](http://us2.php.net/manual/en/function.get-called-class.php)中,加入在PHP 5.3。在早期版本中做這件事有點棘手。 – Charles 2010-06-27 02:39:51
謝謝查爾斯,更新瞭解決這個問題的答案。 – 2010-06-27 02:56:32
聖騎,這是可怕的。想象一下,調用'getInstance'十次,這是十幾次打開和十幾次讀取類文件。 – Charles 2010-06-27 03:01:57