Home > Backend Development > PHP Tutorial > php design pattern singleton

php design pattern singleton

WBOY
Release: 2016-08-08 09:29:33
Original
896 people have browsed it

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

class Single{
//Static methods can only reference static variables
private static $_instance;

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

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

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;
Copy after login
if($danli===$dandi){
echo 'total'; //完全相等
}
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template