Heim  >  Artikel  >  Backend-Entwicklung  >  php设计模式单例

php设计模式单例

WBOY
WBOYOriginal
2016-08-08 09:29:33850Durchsuche

为让一个类只有一个实例,没有克隆

class Single{
//静态方法只能引用静态变量
private static $_instance;

//防止外部使用new创建对象,单例类不能在其它类实例化,只能被自身类实例化

private function __construct(){
echo 'this is a only ';
}
//需要获取静态方法,返回唯一实例的引用

public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance =new self;
}
return self::$_instance;
}

}

$dan1=Single::$_instance;
//dan2和dan1对象完全一样,但由于dan1的静态方法已经创建自身实例,
//所以dan2只是返回实例引用
$dan2=Single::$_instance;
if($danli===$dandi){
echo 'total'; //完全相等
}

主要应用:

1.数据库应用:使用单例避免大量new浪费的资源

2.系统需要全局类来控制某些配置信息

3.页面请求,便于调试


以上就介绍了php设计模式单例,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn