To achieve this purpose, you must ensure that only one instance exists in the project and provide an access point for global access. In this case, you need to call a shared static method of this class to access this instance. That is to say, this class cannot be instantiated outside the class and can only be accessed within the class, in addition, instances can only be called through the shared static method;
I recently read a book on php advanced programming design, pattern, framework, and testing. I am very touched and want to share with you:
During project development, we usually want some class instances to be enough at a time, such as shared configuration classes, template operation classes, and database connections. These classes are common in the development of the entire project, if the instance is used for multiple times, the resource will be occupied.
To achieve this purpose, you must ensure that only one instance exists in the project and provide an access point for global access. In this case, you need to call a shared static method of this class to access this instance. That is to say, this class cannot be instantiated outside the class and can only be accessed within the class, in addition, instances can only be called through the shared static method;
So how can we ensure that this class cannot be instantiated outside? This Singleton class must have a constructor _ construct and be set to private (because _ construct already exists, the default constructor is not considered: directly use the class name method), so that it will not be directly instantiated outside! At the same time, you also need to declare a static method variable to save such an instance, a shared static method to access this instance (because it is shared, so declared as static, store the shared code area in the memory ). You also need to create an empty private _ clone () method to prevent cloning.
A typical Singleton class is as follows:
The Code is as follows: |
Copy code |
Class Simple { /** * Singleton instance * * @ Static * @ Var object Simple */ Public static $ _ instance; // Other member variables /** * Constructor * * @ Return void */ Private function _ construct () { // Write Constructor } /** * Singleton mode call Method * * @ Static * @ Return object Template */ Public static function getInstance () { If (! Self: $ _ instance instanceof self) Self: $ _ instance = new self (); Return self: $ _ instance; } /** * Declare an empty private clone method * */ Private function _ clone () { } // Other methods } // Call Method $ Simple = Simple: getInstance (); ?> |
The instanceof keyword is used above. It is a comparison operator and returns a Boolean value to determine whether an object instance is of a specified type, whether it inherits from a class, or whether it has implemented a specific interface.