Home  >  Article  >  Backend Development  >  Application Analysis Based on Singleton Pattern in PHP Design Pattern_PHP Tutorial

Application Analysis Based on Singleton Pattern in PHP Design Pattern_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:10:13806browse

Singleton pattern: Simply put, an object is only responsible for one specific task.

Singleton class:
1. The constructor needs to be marked as private. The singleton class cannot be instantiated in other classes, but can only be instantiated by itself
2. Have a Save the instance static member variables of 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 the object 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 singleton mode can avoid a large number of resources consumed by 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 section of ZF
3. Request summary on one page for easy debugging, because all the code is concentrated in one class, we can set hooks in the class and output logs, thus avoiding var_dump and echo everywhere.

Copy code The code is as follows:

class DanLi{
// Static member variables
private static $_instance;
//Private constructor
private function __construct(){
}
//Prevent the object from being cloned
public function __clone(){
         trigger_error('Clone is not allow!',E_USER_ERROR); :$_instance = new self;
     }
         return self::$_instance;             ;

//Error: $danli = new DanLi(); $danli_clone = clone $danli;
//Correct: $danli = DanLi::getInstance(); $danli->test() ;

?>






http://www.bkjia.com/PHPjc/327158.html

www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/327158.html

TechArticleSingle case mode: Simply put, an object is only responsible for a specific task. Singleton class: 1. The constructor needs to be marked as private. A singleton class cannot be instantiated in other classes and can only be instantiated by itself...
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