What is the purpose of using the Singleton pattern in PHP, and how does it ensure only one instance of a class is created?
The Singleton pattern in PHP is used to ensure that only one instance of a class is created throughout the application. This is useful when you want to restrict the instantiation of a class to only one object. It can be implemented by providing a static method that returns the same instance of the class each time it is called.
class Singleton {
private static $instance = null;
private function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
// Usage
$singletonInstance = Singleton::getInstance();