什么是单例模式:就是某一个类只有一个实例,并且对外提供这个实例的访问入口
单例模式的好处:防止一个类实例化多次,消耗不必要的内存,增加代码实行速度
<?php
/**
* 未使用单例模式的代码
*/
class single
{
function __construct()
{
}
function __destruct() {
echo "#########<br>";
}
}
$obj = new single();
$obj = new single();
$obj = new single();
$obj = new single();
$obj = new single();
未使用单例模式的代码single这个类被实例化和销毁了5次
/**
* 单例模式
*/
class single
{
static $obj = null;
// 把构造函数设置成私有的这样为了防止外面实例化该类
private function __construct() {
}
static function getobj() {
if (!(self::$obj instanceof self)) {
self::$obj = new self();
}
return self::$obj;
}
public function __destruct() {
echo "###############<br>";
}
}
$obj = single::getobj();
$obj = single::getobj();
$obj = single::getobj();
$obj = single::getobj();
$obj = single::getobj();
使用单例模式的代码single这个类被实例化销毁了1次,从过这次比较可以看出单例模式比较节省内存,代码运行速度会更快.