Singleton Design Pattern in PHP5
Implementing the Singleton design pattern in PHP5 involves creating a class that can have only one instance, regardless of how many times it's instantiated. This is achieved by using a static variable to store the single instance and preventing cloning or de-serialization.
Here's an example of how to create a Singleton class in PHP5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
This implementation uses a static variable $inst to store the single instance of the UserFactory class. The Instance() method serves as the singleton getter. If $inst is null, a new instance is created and assigned to $inst.
To use this Singleton class, simply call the Instance() method to obtain the single instance:
1 2 |
|
Comparing $fact and $fact2 will yield true, confirming that they are the same instance.
However, attempting to instantiate a new UserFactory object directly using new UserFactory() will throw an error because the constructor is made private. The only way to obtain an instance of the UserFactory class is through the Instance() method.
The above is the detailed content of How to Implement the Singleton Design Pattern in PHP5?. For more information, please follow other related articles on the PHP Chinese website!