When using the Singleton pattern in PHP, is it recommended or allowed to inherit from a Singleton class?
In general, it is not recommended to inherit from a Singleton class as it can lead to unexpected behavior and violate the Singleton pattern's intention of having only one instance of a class. If inheritance is necessary, it's better to use composition over inheritance to achieve the desired functionality without breaking the Singleton pattern.
class Singleton {
private static $instance;
protected function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}
}
class Subclass extends Singleton {
// implementation of Subclass
}
$singletonInstance = Subclass::getInstance();
Related Questions
- Are there any best practices or guidelines for including external files or libraries in PHP scripts to avoid errors like "Call to undefined function"?
- How can PHP be used to manipulate user input in HTML forms?
- What are some best practices for error handling and validation when implementing a PHP script to read a file and send its contents via email?