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 函数实例化类,返回一个静态变量的实例,每次通过函数调用,实际上也是初始化一次这个类,这不也是单例模式吗?这种方式有什么潜在的问题呢?