Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance.
Here’s an example of implementing the Singleton pattern in PHP:
class Singleton { // Hold the class instance. private static $instance = null; // The constructor is private to prevent instantiation from outside the class. private function __construct() {} // The getInstance method returns the singleton instance of the class. public static function getInstance() { if (self::$instance == null) { self::$instance = new Singleton(); } return self::$instance; } // Example method of the singleton class. public function someMethod() { return "This is an example method of the Singleton class."; } } // Usage: $instance1 = Singleton::getInstance(); $instance2 = Singleton::getInstance(); // $instance1 and $instance2 will be the same instance. echo $instance1 === $instance2 ? "Same instance" : "Different instances"; // Output: Same instance echo $instance1->someMethod(); // Output: This is an example method of the Singleton class.
In this example:
- We have a private static variable
$instance
which holds the instance of the class. - The constructor
__construct()
is private, so it cannot be accessed from outside the class. - The
getInstance()
method is public and responsible for creating or returning the single instance of the class. - The
someMethod()
method is an example of a method in the Singleton class.
When using the Singleton pattern, you retrieve the instance of the class using getInstance()
method, which ensures that only one instance of the class is created and returned each time.
Leave a Reply