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

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

问题描述

如何使用PHP5类创建一个Singleton类?

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 instance it
     *
     */
    private function __construct()
    {

    }
}

要使用:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

$ fact == $ fact2;

$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中创建Singleton设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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