【发布时间】:2010-07-13 13:24:00
【问题描述】:
所以,我总是像这样实现一个单例:
class Singleton {
private static $_instance = null;
public static function getInstance() {
if (self::$_instance === null) self::$_instance = new Singleton();
return self::$_instance;
}
private function __construct() { }
}
但是,最近让我感到震惊的是,我也可以使用成员级静态变量来实现它:
class Singleton {
public static function getInstance() {
//oops - can't assign expression here!
static $instance = null; // = new Singleton();
if ($instance === null) $instance = new Singleton();
return $instance;
}
private function __construct() { }
}
对我来说,这更干净,因为它不会弄乱类,而且我不必进行任何显式存在检查,但是因为我从未在其他任何地方看到过这种实现,我想知道:
使用第二个实现而不是第一个有什么问题吗?
【问题讨论】:
-
第二种方式也可以作为普通函数实现,我有时也用这个,比如
i()->DB()。 -
+1 好问题和有趣的答案
-
@Alix:我不关注。
getInstance函数如何非静态实现并且仍然适用于单例? -
@Austin Hyde:他指的是常规函数,而不是方法。但是,这将违反单例规则,即应该只存在一个实例,因为它需要一个公共构造函数。它只是一个方便的函数,不必每次都实例化对象。
-
@ircmaxell:啊。这更有意义。感谢您的澄清。
标签: php design-patterns singleton