当前位置: 移动技术网 > IT编程>软件设计>设计模式 > PHP实现单例模式

PHP实现单例模式

2018年10月30日  | 移动技术网IT编程  | 我要评论
<?php
/**
* 单例模式实现
*/
class singleton
{
    //静态变量保存全局实例
    private static $instance = null;

    private function __clone()
    {
        //私有构造函数,防止外界实例化对象
    }

    private function __construct()
    {
        //私有克隆函数,防止外界克隆对象
    }

    //静态方法,单例统一访问入口
    public static function getinstance()
    {
        if (self::$instance instanceof singleton) {
            echo "return exist instance\n";
            return self::$instance;
        }
        self::$instance = new singleton();
        echo "return new instance\n";
        return self::$instance;
    }
}

$a = singleton::getinstance();//output: return new instance
$a = singleton::getinstance();//output: return exist instance

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网