How can the Singleton design pattern be implemented in PHP to ensure a single instance of a class is used throughout the application?
The Singleton design pattern ensures that only one instance of a class is created and used throughout the application. This can be implemented in PHP by creating a private static property to hold the single instance of the class, a private constructor to prevent external instantiation, and a static method to provide access to the single instance.
class Singleton {
private static $instance;
private function __construct() {
// private constructor to prevent external instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}