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;
}
}
Related Questions
- What are some common mistakes to avoid when working with PHP and MySQL together in a web development project?
- What are some alternative methods, besides manual editing or using UltraEdit, to efficiently replace multiple occurrences of a pattern in a PHP file?
- In what scenarios would it be more efficient to use pre-existing libraries or tools for parsing content, such as the BBCode library mentioned in the forum thread?