我正在一个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