关于 PHP 单例模式的疑问

2015-10-26 11:37:12 +08:00
 tanteng

PHP 实现单例模式的类大概如下:

class TestInstance
{
    public static $_instance = null;
    public static $_count=0;//用来计数实例化的次数
    protected function __Construct()
    {
        echo 'Instance,Instance,Instance..........';
        echo "<br>";
    }

    public static function getInstance()
    {
        if(isset(self::$_instance) && self::$_instance instanceof self){
            return self::$_instance;
        }else{
            self::$_count++;
            self::$_instance = new static();
            return self::$_instance;
        }
    }
}

在需要用的地方这样:

$aa == TestInstance::getInstance();
$bb == TestInstance::getInstance();
$cc == TestInstance::getInstance();

这样用肯定没错,我要问的是下面这种方式:

首先定义一个普通的类和一个全局函数:

//demo.class.php
class Demo
{
    public function __Construct()
    {
        //TODO
    }
}

//functions.php 全局函数
function get_obj()
{
    static $obj;
    if($obj){
        return $obk;
    }else{
        $obj = new Demo();
        return $obj;
    }
}

在用的地方使用这个 get_obj 函数获取类的实例:

$aa = get_obj();
$aa->xx();

$bb = get_obj();
$bb->xx()

第二种方式,并没有定义一个实现单例模式的类,通过 get_obj 函数实例化类,返回一个静态变量的实例,每次通过函数调用,实际上也是初始化一次这个类,这不也是单例模式吗?这种方式有什么潜在的问题呢?

2305 次点击
所在节点    PHP
6 条回复
tanteng
2015-10-26 11:49:24 +08:00
更正:
$aa = TestInstance::getInstance();
$bb = TestInstance::getInstance();
$cc = TestInstance::getInstance();
ljmready
2015-10-26 12:07:15 +08:00
这样做吃相不好,封装到一个类里,比较优雅。。。吧。
djyde
2015-10-26 12:12:40 +08:00
心疼写 php 的
wingoo
2015-10-26 12:32:17 +08:00
使用单例的意义是什么
无非就是复用, 节约创建对象的成本

这个搞清楚了, 那就清楚了
当然你还要尽可能的搞的漂亮些, 考虑的全面些
所以都可以啦, 看你自己的情况

貌似说了一堆废话:)
Zzzzzzzzz
2015-10-26 12:42:58 +08:00
团队协作时要是有人忘了是单例直接 new class, 第一种一运行就出错, 第二种可能要出了事才会发现, 早暴露比晚暴露好。

php4 时代没方法的权限控制和真正的静态方法, 第二种方法有遗留代码会用, 但并不提倡。
tanteng
2015-10-26 12:56:20 +08:00
@djyde 此言何意?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/231105

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX