This article provides a detailed analysis of the application of the single-sample php design mode. For more information, see
Singleton mode: simply put, an object is only responsible for a specific task.
Singleton class:
1. the constructor must be marked as private. the singleton class cannot be instantiated in other classes and can only be instantiated by itself.
2. have a static member variable for the instance that saves the class
3. have a public static method to access this instance. [The getInstance () method is commonly used to instantiate a singleton class. the instanceof operator can detect whether the class has been instantiated]
Note: You need to create the _ clone () method to prevent objects from being copied.
Purpose:
1. php applications are mainly used for databases. 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 it using the Singleton mode. Refer to the ZF FrontController section.
3. summary of requests on a page for debugging. because all the code is concentrated in a class, we can set hooks in the class and output logs to avoid var_dump and echo everywhere.
The code is as follows:
Class DanLi {
// Static member variable
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 );
}
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 ();
?>