PHP Singleton mode copyright statement:
Author: Toutiao.com/Mizuho technology
Link: http://toutiao.com/i6282868901994824193/
Source: Toutiao.com (Toutiao.com's creation platform)
If you want to reprint the information, please contact Yi Xiaoyi, a member of the cloud College team, at: ruanqy # tingyun.com
The Singleton mode is the creation mode. what is the creation mode? that is, the creation mode abstracts the instantiation process. They help a system to create, combine, and represent its objects independently. A class creation mode uses inheritance to change the class to be instantiated. In the creation mode, an object is instantiated and delegated to another object.
Overview: ensure that a class has only one instance and provides a global access point to it.
Prerequisites:
1. the constructor needs to be marked as private (access control: prevents external code from using the new operator to create objects). a singleton class cannot be instantiated in other classes but can only be instantiated by itself.
2. static member variables of an instance that stores classes
3. there is a public static method to access this instance (the getInstance () method is often used to instantiate the singleton class, and the instanceof operator can detect whether the class has been instantiated)
4. create the _ clone () method to prevent objects from being copied (cloned)
Why is the singleton mode used?
1. php applications mainly lie in database applications. Therefore, a large number of database operations exist in an application. Using the Singleton mode can avoid the resources consumed by a large number of new operations.
2. if you need a class in the system to globally control some configuration information, you can easily implement. Config using the Singleton mode.
3. in a page request, debugging is easy, because all the code (such as database operation db) is concentrated in one class. we can set hooks in the class and output logs, this avoids var_dump and echo everywhere.
Code instance
try{$singleObj = \haibao\design\web\common\design\single\Single::getInstance();//$singleObj1 = clone $singleObj;echo $singleObj->getData();}catch (\Exception $e){echo $e->getMessage();exit;}
".rand(1,100)."
";}}
For more technical articles, visit the cloud technology blog and visit the official cloud website to learn more about the magic of application performance optimization.