Unlike normal classes, a singleton class cannot be directly instantiated in other classes. A singleton class can only be instantiated by itself. to obtain this restriction, you must mark the constructor as private. To make the singleton class take effect, you must provide an instance for other classes and use it to call various methods. As a model
Unlike normal classes, a singleton class cannot be directly instantiated in other classes. A singleton class can only be instantiated by itself. to obtain this restriction, you must mark the constructor as private. To make the singleton class take effect, you must provide an instance for other classes and use it to call various methods. As part of this mode, you must create an empty private _ clone () method to prevent objects from being copied and cloned. The Singleton is summarized as follows:
1. they must have a constructor marked as private.
2. they have a static member variable that saves the class instance.
3. they have a public static method to access this instance. The instance code is as follows:
Flat view printing?
05 |
// Store the static variables of an instance |
06 |
Privatestatic $ _ instance; |
08 |
// Construct a private method |
09 |
Privatefunction _ construct () |
11 |
$ This-> _ db = mysql_connect ('localhost', 'root', 'admin '); |
13 |
// Prevent the object from being cloned |
14 |
Privatefunction _ clone () |
17 |
PublicstaticfunctiongetInstance () |
19 |
// Prevent multiple instances |
20 |
If (! (Self: $ _ instanceinstanceof self )) |
22 |
Self: $ _ instance = newself (); |
24 |
Returnself: $ _ instance; |
27 |
Publicfunctionquery () |
32 |
PublicfunctionselectDB () |
39 |
// Obtain the instance of the class |
40 |
$ Object = DB: getInstance (); |
43 |
Echo $ object-> query (); |
This class begins to declare two variables, one is the private variable $ _ db storage database connection, will be filled during the construction, and the other is used for storage class instances. The next step is private constructor and magic function clone, which can prevent classes from being instantiated and cloned externally. the getInstance static method is used for the worker class instance. the code here can ensure the existence of a single instance, reduce system resource consumption and return instance references.