Overview:
As an object's creation pattern, a singleton ensures that only one instance exists in an intrinsic system and that it cannot create a copy.
The Clone function (__clone) and the constructor (__construct) must be declared private, preventing the external program from creating a new class and losing the meaning of the singleton pattern.
The PHP language is an interpreted language, and when the page is executed, all related resources are recycled. PHP at the language level, not like the C#,java compiled language, there is no way for an object to long-distance memory.
However, in a single request scenario, it is possible to share objects through a singleton pattern, such as a database connection object.
Class dbconnection{ private static $_instance; private static $token = 0; public static function getinstance () { if (static::$_instance instanceof DbConnection) { return static::$_instance; } Randomly produces a token indicating the current static:: $token = rand (+); Static::$_instance = new DbConnection (); return static::$_instance; } Clone functions and constructors must be declared private, //Prevent external programs from creating a new class, and losing the meaning of singleton patterns. Private Function __clone () { } Private Function __construct () { } Public Function Open () { echo "init times:".) Static:: $token. ' <br/> '; }}
Comparison of a singleton with the static class:
1, Singleton can be very good to maintain the object's face object, such as static tool class can use static.
2, a single case can be implemented from an interface, can inherit from a class. A static class can also inherit from a class, but it is impossible to use a protect member within the parent class.
PHP Design Patterns-Singleton