How does the use of get_called_class() affect the implementation of the Singleton pattern in PHP?
When implementing the Singleton pattern in PHP, using get_called_class() can help ensure that the correct subclass is instantiated as a Singleton. This is especially useful when working with inheritance and wanting to maintain a single instance of each subclass. By using get_called_class(), the Singleton pattern can be implemented in a more flexible and robust way.
class Singleton {
private static $instances = [];
public static function getInstance() {
$class = get_called_class();
if (!isset(self::$instances[$class])) {
self::$instances[$class] = new $class();
}
return self::$instances[$class];
}
protected function __construct() {
// prevent direct instantiation
}
private function __clone() {
// prevent cloning
}
}
class Subclass1 extends Singleton {
// additional subclass logic
}
class Subclass2 extends Singleton {
// additional subclass logic
}
$instance1 = Subclass1::getInstance();
$instance2 = Subclass2::getInstance();
var_dump($instance1 === Subclass1::getInstance()); // true
var_dump($instance2 === Subclass2::getInstance()); // true
Related Questions
- What are common PHP syntax errors that can lead to a "parse error" like the one mentioned in the thread?
- In what scenarios would it be necessary or beneficial to know the specific scope of code execution in PHP?
- In what scenarios would it be more efficient to keep HTML code within PHP files, and how can potential parsing issues be mitigated?