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
- How can PHP be used to handle the storage and retrieval of stock prices in a database?
- What is the best approach to format a phone number in PHP with a specific pattern, considering varying lengths of the input string?
- What are the best practices for handling situations where PHP is not installed or not functioning correctly?