This article will introduce you to the singleton mode method of PHP design pattern examples. Friends who need to know more can enter it for reference.
Single instance class:
1. The constructor needs to be marked as private. A singleton class cannot be instantiated in other classes, but can only be instantiated by itself
2. Have an instance static member variable that saves the class
3. Have a public static method to access this instance. [The getInstance() method is commonly used to instantiate singleton classes, and the instanceof operator can be used to detect whether this class has been instantiated]
Note: You need to create a __clone() method to prevent objects from being copied
Function:
1.php applications are mainly used for databases, so there will be a large number of database operations in an application. Using the singleton mode can avoid the resources consumed by a large number of new operations
2. If a class is needed in the system to globally control certain configuration information, it can be easily implemented using the singleton mode. Refer to the FrontController part of ZF
3. Request summary on one page to facilitate debugging, because all the code is concentrated in one class, we can set hooks in the class and output logs, thereby avoiding var_dump and echo everywhere.
Example of PHP singleton pattern.
The code is as follows |
Copy code |
代码如下 |
复制代码 |
/**
* 单例模式
*/
class DanLi{
//静态成员变量
private static $_instance;
//私有的构造方法
private function __construct(){
}
//防止对象被克隆
public function __clone(){
trigger_error('Clone is not allow!',E_USER_ERROR);
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self;
}
return self::$_instance;
}
public function test(){
echo "ok";
}
}
//错误:$danli = new DanLi(); $danli_clone = clone $danli;
//正确:$danli = DanLi::getInstance(); $danli->test();
?>
|
/**<🎜>
* Singleton mode<🎜>
<🎜>*/<🎜>
class DanLi{<🎜>
//Static member variables<🎜>
Private static $_instance;<🎜>
//Private construction method<🎜>
Private function __construct(){<🎜>
}<🎜>
//Prevent objects from being cloned<🎜>
Public function __clone(){<🎜>
trigger_error('Clone is not allow!',E_USER_ERROR);<🎜>
}<🎜>
Public static function getInstance(){<🎜>
If(!(self::$_instance instanceof self)){<🎜>
self::$_instance = new self;<🎜>
}<🎜>
return self::$_instance;<🎜>
}<🎜>
Public function test(){<🎜>
echo "ok";<🎜>
}<🎜>
}<🎜>
<🎜>
//Error: $danli = new DanLi(); $danli_clone = clone $danli;<🎜>
//Correct: $danli = DanLi::getInstance(); $danli->test();
?>
|
Let’s discuss why we should use PHP singleton mode?
Most people understand its purpose from the literal meaning of the singleton pattern, thinking that it saves system resources, avoids repeated instantiation, and is a kind of "family planning". And PHP executes it every time All resources will be cleared from memory when the page is completed. Therefore, the singleton in PHP actually needs to be re-instantiated every time it is run, thus losing the meaning of repeated instantiation of the singleton. From this aspect alone It is said that PHP's singleton is indeed a bit disappointing to everyone. But does a singleton only have this function and application? The answer is no, let's take a look.
1. PHP is mainly used in database applications, so there will be a large number of database operations in an application. When developing in an object-oriented way (nonsense), if you use the singleton mode, you can avoid a lot of new operation consumption. resources.
2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode. This can be found in the FrontController part of zend Framework.
3. In a page request, it is easy to debug because all the code (such as database operation class db) is concentrated in one class. We can set hooks in the class and output logs to avoid var_dump and echo everywhere. .
The code is as follows
代码如下 |
复制代码 |
/**
* 设计模式之单例模式
* $_instance必须声明为静态的私有变量
* 构造函数和析构函数必须声明为私有,防止外部程序new
* 类从而失去单例模式的意义
* getInstance()方法必须设置为公有的,必须调用此方法
* 以返回实例的一个引用
* ::操作符只能访问静态变量和静态函数
* new对象都会消耗内存
* 使用场景:最常用的地方是数据库连接。
* 使用单例模式生成一个对象后,
* 该对象可以被其它众多对象所使用。
*/
class Example
{
//保存例实例在此属性中
private static $_instance;
//构造函数声明为private,防止直接创建对象
private function __construct()
{
echo 'I am Construceted';
}
//单例方法
public static function singleton()
{
if(!isset(self::$_instance))
{
$c=__CLASS__;
self::$_instance=new $c;
}
return self::$_instance;
}
//阻止用户复制对象实例
public function __clone()
{
trigger_error('Clone is not allow' ,E_USER_ERROR);
}
function test()
{
echo("test");
}
}
// 这个写法会出错,因为构造方法被声明为private
$test = new Example;
// 下面将得到Example类的单例对象
$test = Example::singleton();
$test->test();
// 复制对象将导致一个E_USER_ERROR.
$test_clone = clone $test;
?>
|
|
Copy code |
|
/**
* Design Pattern Singleton Pattern
* $_instance must be declared as a static private variable
* Constructors and destructors must be declared private to prevent external programs from new
* The class thus loses the meaning of the singleton pattern
* The getInstance() method must be set to public and this method must be called
* to return a reference to the instance
*::Operator can only access static variables and static functions
* new objects will consume memory
* Usage scenario: The most commonly used place is database connection.
* After using singleton mode to generate an object,
* This object can be used by many other objects. */
class Example
{
//Save the example instance in this attribute
private static $_instance;//The constructor is declared as private to prevent direct creation of objects<🎜>
private function __construct()<🎜>
{<🎜>
echo 'I am Construceted';<🎜>
}<🎜>
<🎜>//Single case method<🎜>
public static function singleton()<🎜>
{<🎜>
if(!isset(self::$_instance))<🎜>
{<🎜>
$c=__CLASS__;<🎜>
self::$_instance=new $c;<🎜>
}<🎜>
return self::$_instance;<🎜>
}<🎜>
<🎜>//Prevent users from copying object instances<🎜>
public function __clone()<🎜>
{<🎜>
trigger_error('Clone is not allow' ,E_USER_ERROR);<🎜>
}<🎜>
<🎜>function test()<🎜>
{<🎜>
echo("test");<🎜>
<🎜>}<🎜>
}<🎜>
<🎜>// This way of writing will be wrong because the constructor is declared as private<🎜>
$test = new Example;<🎜>
<🎜>//The following will get the singleton object of the Example class<🎜>
$test = Example::singleton();<🎜>
$test->test();
// Copying the object will result in an E_USER_ERROR.
$test_clone = clone $test;
?>
http://www.bkjia.com/PHPjc/628780.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628780.htmlTechArticleThis article will introduce you to the singleton mode method of PHP design pattern examples. Friends who need to know more can enter for reference. refer to. Singleton class: 1. The constructor needs to be marked private, singleton classes do not...