Singleton mode (duty mode):
Simply put, an object (before learning design patterns, need to understand the object-oriented thinking) is only responsible for a specific task;
Singleton class:
1. Theconstructor needs to be marked as private(access control: Prevent external code from creating objects using the new operator), the Singleton class cannot be instantiated in other classes, and can only be instantiated by itself;
2.have a static member variable that holds an instance of the class
3, has a public access to this instance of the static method (common getinstance () method to instantiate a singleton class, through the instanceof Operator can detect if the class has been instantiated)
In addition, you need to create a __clone () method to prevent the object from being copied (cloned)
Why use php Singleton mode?
1, php , So there's a lot of database operations in an app using singleton mode , new The resources consumed by the operation.
2, If a class is required in the system to globally control some configuration information ,  .  This can be see Zf part.
3, in a page request ,  easy to debug Because all the code example Database Operations class DB) All concentrated in one class , We can set hooks in the class , output the log, thus avoiding everywhere var_dump, echo
Code implementation:
<php
/1**
* Design pattern of a single case mode
* $_instance must be declared as a static private variable
* Constructors and destructors must be declared private to prevent external program new class to lose the meaning of a singleton pattern
* The getinstance () method must be set to public, 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 common place is the database connection.
* Once an object is generated using singleton mode,
* This object can be used by many other objects .
*/
class Danli {
To save a static member variable for a class instance
private static $_instance;
How to construct private tags
Private Function __construct () {
Echo ' This is a constructed method; ' ;
}
To create a __clone method to prevent an object from being cloned
Public Function __clone () {
Trigger_error (' Clone is not allow! ' , e_user_error);
}
A singleton method, a public static method for accessing an instance
public static function getinstance() {
If(! (self::$_instance instanceof self)){
Self::$_instance = new self;
}
Return self::$_instance;
}
Public Function Test () {
Echo ' Invoke method succeeded ';
}
}
Class with new instantiation of private tag constructor will error
$danli = new Danli ();
Correct method, use double colon:: operator to access the static method to get the instance
$danli = Danli::getinstance();
$danli->test ();
Copying (cloning) an object will result in a e_user_error
$danli _clone =Clone$danli;
Single-Case mode