Home >Backend Development >PHP Tutorial >Detailed explanation of PHP object instantiation singleton method
Single case mode (responsibility mode):
Simply put, an object (before learningDesign pattern, you need to understand object-oriented thinking) is only responsible for a specific task;
Single instance class:
1, Constructor needs to be marked as private (Access control: Prevent external code from using the new operator Create an object), a singleton class cannot be instantiated in other classes, but can only be instantiated by itself;
2. Have a static member variable that holds an instance of the class
3. Have a public static method to access this instance (the getInstance() method is commonly used to instantiate a singleton class, and the instanceof operator can be used to detect whether the class has been instantiated)
In addition, a clone needs to be created () method prevents the object from being copied (cloned)
Why use PHP singleton mode?
1. The application of PHP mainly lies in database applications, so there will be a large number of database operations in an application. Using singleton mode can avoid a large number of resources consumed by new operations.
2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode. This can be found in the FrontController section of ZF.
3. In a page request, it is easy to debug because all the code (such as database operation class db) is concentrated in one class. We can set hooks in the class and output logs to avoid everywhere var_dump, echo.
This article mainly introduces the method of instantiating objects singletons in PHP, which has a very good reference value. Let’s take a look at it with the editor
PHP method of instantiating an object singleton:
Three private and one public: 2 private methods, 1 privateProperties, 1 public method
private function construct(){} //不可以继承构造方法 private function clone(){}//不可以继承克隆方法 privare static $_instance;
一公
public static function getinstance(){ if(!isset(static:$_instance)){ static::$_instance=new static(); } return static::$_instance; }
The above is the detailed content of Detailed explanation of PHP object instantiation singleton method. For more information, please follow other related articles on the PHP Chinese website!