如何使用 PHP5 类创建单例类?
/** * Singleton class * */ final class UserFactory { private static $inst = null; // Prevent cloning and de-serializing private function __clone(){} private function __wakeup(){} /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { if ($inst === null) { $inst = new UserFactory(); } return $inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } }
要使用:
$fact = UserFactory::Instance(); $fact2 = UserFactory::Instance();
$fact == $fact2;
但:
$fact = new UserFactory()
引发错误。
请参阅http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static以了解静态变量范围以及设置static $inst = null;工作的原因。
static $inst = null;