您的位置:首页 > 编程语言 > PHP开发

PHP单例模式讲解

2014-04-07 17:11 260 查看

最近研究了一下discuz的源码,涉及到单例设计模式,做个笔记。

单例模式就是确保一个类只有一个实例,并且是自行实例化。
三个要点:
1、保存唯一实例的静态成员变量;
2、构造函数私有化;
3、访问这个实例的公共的静态方法(通常为getInstance方法),返回唯一实例的一个引用
代码如下:
<?php
class test{
private static $_instance;
private $v="";
private function __construct(){
}
static public function getinstance(){
if(!self::$_instance instanceof self){
self::$_instance = new self;
}
return self::$_instance;
}
public function set($s){
$this->v.=$s;
}
public function show(){
echo $this->v;
}

}
?>


测试是否同一个实例:
<?php
require_once('danli.class.php');
$t=TEST::getinstance();
$t->set('hello world');
$t->show();
echo '<br>';
$t2=TEST::getinstance();
$t2->set('----hello world');
$t2->show();
?>


输出结果为:

hello world

hello world----hello world



这段代码中,$t为该类的一个实例,通过set方法设置了test类的成员变量$v的值,然后输出hello world;$t2指向的也是同一个实例,为什么这么说?因为$t2也调用了test类的set方法,如果$t和$t2表示的不是同一个实例的话,那输出的结果应该是

hello world

----hello world



但实际结果并不是这样,所以,流程应该是$t通过set方法设置了成员变量$v的值,此时$v=='hello
world';然后$t2也调用了set方法设置了$v的值,因为他们是同一个实例,所以$v=='hello world----hello world'。


下面给个普通类的对比例子:
这是一个普通类:
<?php
class test{
private $v="";
public function set($s){
$this->v.=$s;
}
public function show(){
echo $this->v;
}

}
?>


测试:
<?php
require_once('putong.class.php');
$t=new test();
$t->set('hello world');
$t->show();
echo '<br>';
$t2=new test();
$t2->set('----hello world');
$t2->show();
?>


输出结果为:

hello world

----hello world


上面的这段代码test有两个实例$t,$t2,他们表示两个不同的实例,所以他们输出的内容各不相关,通过set方法设置了什么就输出什么。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: