Home > Article > Backend Development > PHP design pattern singleton pattern learning
The program running result is: Fatal error: Call to private A::__construct() from invalid context in E:PHPProjectstest.php on line 6 We have prohibited the external use of new to instantiate this class. How do we allow users to access this class? The front door is blocked, we need to leave a back door for users.
The solution is: static modified method, you can directly access this method without instantiating a class.
//Classes that cannot be instantiated with new.
The program running result is: The class of $a1 is A , $a2 is A $a1 $a2 is not an object. We have returned the instance of A through the static method. But there's still a problem. How do we ensure that we obtain the same instance through multiple operations? Solution:
There is only one static attribute internally.
Static attributes can be effectively called by static methods. Also set this property to private to prevent external calls.
First set this property to null. Before each return of the object, first determine whether this property is null.
If null, create a new instance of this class and assign it to this static property. If it is not empty, return the static property pointing to the instance.
//Classes that cannot be instantiated with new.
The program running result is: The class of $a1 is A , $a2 is A $a1 $a2 point to the same object. At this point, we have written the simplest singleton pattern. Now, you can try to write a database connection class that applies the singleton design pattern. Remember the usage and writing methods of the singleton pattern. |