0

(Solved)Why a second instance is created in the Singleton Code below?

I tried to implement a singleton in PHP.Everything is OK- the constructor can not be inistated from outside the class,the getter Method creates a new Object. But when I try to call the getinstance method which returns the only instance of this class by calling the constructor, a second time the constructor is called a second time. But I thought the singleton patters states that there is only possible instance so the constructor should also be called only once when the instance is created? Is my definiton wrong or is/are there any mistace(s) in my Code https://code.sololearn.com/w7AW9YBj9SAK/?ref=app https://code.sololearn.com/w7AW9YBj9SAK/?ref=app https://code.sololearn.com/w7AW9YBj9SAK/?ref=app

12th Sep 2018, 5:01 PM
hans
hans - avatar
4 Answers
+ 1
You don't correctly save the instance in your static variable. Your code should look like this: public static function getinstance (){ if(singleton::$instance ===null){ singleton::$instance =new singleton(); } return singleton::$instance; }
12th Sep 2018, 7:33 PM
John Wells
John Wells - avatar
+ 1
self::name could be used in place of class::name. However, it only matters when a subclass overrides a method. self::name will find the subclass version, while class::name won't.
12th Sep 2018, 9:06 PM
John Wells
John Wells - avatar
+ 1
Without self:: or singleton:: in front of $instance, you created a local variable with your new statement.
12th Sep 2018, 9:11 PM
John Wells
John Wells - avatar
0
Ok Thank you now the code is working. But I still have a few other questions Is the singleton Value before the $instance Variable necessary in Order to call the static Variable $instance within that class? Wh it didnt't work with the self reference? I thought the Keyword self is referencing to the actual class in wich I try to get the Variable So I thought with self::$instance I am referencing to the instance Variable in the class Or am I wrong? Thank you for your time reading this and for the answer.
12th Sep 2018, 8:15 PM
hans
hans - avatar