如何使用 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;
的原因。
关于php - 在 PHP5 中创建单例设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/203336/