It is said that Singleton mode is the simplest of the design patterns.
Not much to say, first on the code, then the commentary, altogether two files:
Danli.class<?PHPclassDanli {//to save a static member variable for an instance of a class Static Private$_instance=NULL; //Private method of construction Privatefunction __construct () {echo"This is a construction method <br>"; } //public static method for accessing an instance of a class Static Publicfunction getinstance () {if(!(self::$_instance instanceof Danli)) {echo"instantiation <br>"; Self::$_instance=NewSelf ; } returnself::$_instance; } //other methods of the class Publicfunction Test () {echo"Call Success <br>"; } }
index.php <? PHP // Load class file " danli.php " ; // first invocation of an instance of a class $first = danli::getinstance (); $first, Test (); // second invocation of an instance of a class $second = danli::getinstance (); $second->test ();
Output: instantiation This is a successful invocation of a constructor method call successfully
The above is a simple implementation of PHP singleton mode, the result can be seen that the Danli class was only instantiated once.
Now let's talk about the singleton mode.
Simply put, the singleton mode is to make an object of the class become the only instance in the system, avoid a lot of resources consumed by the new operation, and conveniently set the hook output log information.
About the singleton mode in the online can receive a lot of very detailed commentary, here no longer repeat, let's talk about PHP in detail the implementation of a singleton mode.
As can be seen from the code above, PHP's singleton pattern implementation requires:
1, a private __construct is necessary, the Singleton class can not be instantiated in other classes, can only be instantiated by itself;
2. Have a static member variable that holds an instance of the class;
3, a static public method is used to instantiate this class, and access to instances of this class;
PHP Single-instance mode