I want to implement Singleton Design Pattern to a class which extends another class with a public constructor in PHP. For example, consider a class, say Animal:
class Animal
{
public function __construct()
{
}
}
I want to implement Singleton Design Pattern to a class which extends Animal, for example:
class Dog extends Animal
{
protected function __construct()
{
}
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
}
If I try to do Dog::getInstance() it gives an error
Fatal error: Access level to Dog::__construct() must be public (as in class Animal)
But if I make the constructor of class Dog public, then there's no point in implementing Singleton pattern to it.
Is there a workaround so that I can implement Singleton pattern to the class Dog while extending class Animal? OR Is there a better design pattern for achieving what I want?
Thanks.
Aucun commentaire:
Enregistrer un commentaire