So I am in a big mess here. I can say that my questions are few. I tried to make a singleton pattern but it returns me two different objects. This is what I made (saw in another post) and tried to test it.
class Singleton
{
private static $instance = [];
public function __construct(){}
public function __clone(){}
public function __wakeup(){
throw new Exception("Cannot unserialize singleton");
}
public static function getInstance()
{
$class = get_called_class();
if(!isset(self::$instance[$class])){
self::$instance[$class] = new static();
}
return self::$instance[$class];
}
}
class Dog extends Singleton
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
$dog = new Dog("Jorko");
$dog2 = new Dog("Peshko");
echo $dog->name; // returns "Jorko"
echo $dog2->name; // returns "Pesho"
I thought the second object ($dog2
) should not be created and I would get $dog
again. And why are we creating empty __constructor
in the class Singleton
? Also, why are we using this get_called_class
? I mean according to php manual Gets the name of the class the static method is called in.
. That is what it returns but isn't new static
. I thought that new static
do the same thing. I am in a real mess. I searched around the web but can't get it clear in my head. Thank you a lot!