Home  >  Article  >  Backend Development  >  php design pattern singleton

php design pattern singleton

WBOY
WBOYOriginal
2016-08-08 09:29:33875browse

To allow a class to have only one instance, no cloning

class Single{
//Static methods can only reference static variables
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'; //完全相等
}

Main applications:

1. Database application: Use singletons to avoid a lot of new wasted resources

2. The system needs global classes to controlcertain configuration information

3. Page requests for easy debugging


The above introduces the PHP design pattern singleton, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn