In order to achieve this purpose, it is necessary to ensure that the entire project has and only one instance exists and provides an access point for global access. This requires accessing this instance by calling a shared static method of this class, which means that this class cannot be instantiated outside the class, but can only be instantiated inside the class, and the instance can only be called through a shared static method;
I recently read the book PHP Advanced Programming, Patterns, Frameworks and Testing, and I have a lot of insights. I would like to share it with you:
When working on a project, we usually hope that one instance of certain classes is enough, such as shared configuration classes, template operation classes, database connections, etc. These classes are common in the entire project development. If the instances are multiple Instances will occupy resources.
In order to achieve this purpose, it is necessary to ensure that the entire project has and only one instance exists and provides an access point for global access. This requires accessing this instance by calling a shared static method of this class, which means that this class cannot be instantiated outside the class, but can only be instantiated inside the class, and the instance can only be called through the shared static method;
So how to ensure that this class cannot be instantiated outside? This singleton class must have a constructor __construct and set it to private (because there is already __construct, the default construction method is not considered: the method of directly using the class name), so as to ensure that it will not be directly used outside. Instantiate! At the same time, you also need to declare a static method variable to save the instance of this class, and a shared static method to access this instance (because it needs to be shared, it is declared static to store the shared code area in the memory). You also need to create an empty private __clone() method to prevent cloning.
A very typical singleton class is as follows:
The code is as follows
|
Copy code
|
||||
class Simple |
http: //www.bkjia.com/PHPjc/628959.html