How to use singleton pattern in php Design pattern
This article mainly shows you "how to use the singleton pattern in the php design pattern", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use the singleton pattern in the php design pattern" this article.
Singleton pattern: simply put, an object is only responsible for a specific task.
Singleton class:
1. The constructor needs to be marked private, and the singleton class cannot be instantiated in other classes, but can only be instantiated by itself
two。 Have an instance static member variable that holds the class
3. Have a public static method that accesses this instance. [the getInstance () method is commonly used to instantiate the singleton class, and you can detect whether the class has been instantiated by the instanceof operator]
Note: you need to create a _ _ clone () method to prevent objects from being copied
Function:
The application of 1.php is mainly used in database, so there will be a large number of database operations in an application, and using singleton mode can avoid the resources consumed by a large number of new operations.
two。 If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. Refer to the FrontController section of ZF
3. Request summarization on one page, easy to debug, because all the code is concentrated in one class, we can set hooks in the class and output logs to avoid var_dump,echo everywhere.
The copy code is as follows:
These are all the contents of the article "how to use singleton patterns in php Design patterns". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!