在 PHP5 中创建单例设计模式 [英] Creating the Singleton design pattern in PHP5

查看:36
本文介绍了在 PHP5 中创建单例设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP5 类创建单例类?

How would one create a Singleton class using PHP5 classes?

推荐答案

/**
 * Singleton class
 *
 */
final class UserFactory
{
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        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; 有效.

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null; works.

这篇关于在 PHP5 中创建单例设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆