In the classic tutorial of the PHP Singleton mode, first we need to know the concept of Singleton mode. what is Singleton mode?
First, we need to know the concept of Singleton mode. what is Singleton mode?
The Singleton mode, as its name implies, has only one instance.
As the object creation mode,
The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system,
This class is called a singleton class.
The Singleton mode has three main points:
First, a class can only have one instance;
Second, it must create the instance on its own;
Third, it must provide the instance to the entire system.
Next we will discuss why we should use the PHP Singleton mode?
Most people simply understand the purpose of the Singleton model,
This saves system resources and avoids repeated instantiation. it is a kind of "family planning". every time PHP finishes executing the page, all resources will be cleared from the memory.
Therefore, in PHP, the singleton needs to be re-instantiated every time it is run, thus losing the significance of the Singleton repeated instantiation. in this regard, the PHP Singleton is indeed a bit disappointing.
But does the Singleton only have this function and application? The answer is No. let's take a look.
1. php applications mainly lie in database applications. Therefore, a large number of database operations exist in an application,
When using the object-oriented method for development (nonsense), if you use the Singleton mode, you can avoid the resource consumption of a large number of new operations.
2. if the system requires a class to globally control some configuration information,
The Singleton mode can be easily implemented. For more information, see the FrontController section of zend Framework.
3. in a page request,
Debugging is easy, because all the code (such as database operation db) is concentrated in one class. we can set hooks in the class and output logs to avoid var_dump and echo everywhere.