What distinguishes a class as a Singleton in PHP?
A Singleton class in PHP is a class that can only have one instance at a time. This is achieved by making the constructor private and providing a static method to access the single instance. This ensures that no matter how many times the class is instantiated, only one instance is returned.
class Singleton {
private static $instance;
private function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
Related Questions
- How can PHP developers handle multiple search terms efficiently when searching through CSV files?
- What is the recommended practice for formatting numbers with thousand separators in PHP?
- In what ways does the lack of a RestoreSettings() function limit the functionality and usability of the settings class?