How does a Singleton in PHP ensure that only one instance of a class is created?
A Singleton in PHP ensures that only one instance of a class is created by defining a static property to hold the single instance and a static method to access it. The constructor of the class is made private to prevent external instantiation and a static method is used to provide a single point of access to the instance.
class Singleton {
private static $instance;
private function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}