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:
final class UserFactory { private static $inst = null; // Prevent cloning and de-serializing private function __clone(){} private function __wakeup(){} /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { if self::$inst === null) { self::$inst = new UserFactory(); } return self::$inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } }
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:
$fact = UserFactory::Instance(); $fact2 = UserFactory::Instance();
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!