PHP单例模式讲解

最近研究了一下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方法设置了什么就输出什么。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值