The Singleton design pattern is a creational design pattern that allows you to ensure that a class has only one instance, while providing a global point of access to that instance. In PHP, you can implement the Singleton pattern by following these steps:
- Create a class and make its constructor private to prevent the class from being instantiated from outside the class.
- Create a static method that will be used to get the single instance of the class. This method will create a new instance of the class if one does not already exist, or it will return the existing instance.
- Store the single instance of the class in a private static property.
Here’s an example implementation of the Singleton pattern in PHP:
class Singleton {
private static $instance;
private function __construct() {
// Prevents the class from being instantiated from outside the class
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function doSomething() {
// Class method
}
}
In this implementation, the Singleton
class has a private constructor that prevents it from being instantiated from outside the class. The getInstance()
method is a static method that creates a new instance of the Singleton
class if one does not already exist, or it returns the existing instance. The doSomething()
method is a class method that can be used to perform some action.
To use the Singleton
class, you can call the getInstance()
method to get the single instance of the class, and then call its methods:
$singleton = Singleton::getInstance();
$singleton->doSomething();
This will create a single instance of the Singleton
class and call its doSomething()
method. Subsequent calls to getInstance()
will return the same instance.
Thank you😎