php - 在 PHP5 中创建单例设计模式

标签 php oop design-patterns singleton

如何使用 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/

相关文章:

PHP foreach 类别和子类别

Javascript if else 替代品

java - 事后实现接口(interface)

php - 在mysql中查询显示纬度经度多边形

php - 如何通过 .cnf 文件通过 php 更改 mysql 模式?

php - 需要从studentsDB统计页面知道每个城市有多少学生

oop - 首批第一本丛书中的objectville是什么?

python - 如何在 Python 中激活(执行)类的方法?

oop - Nim如何定义构造函数?

java - 构建这个复杂对象的设计模式