All the singleton patterns I have seen use a reference to the object to determine if the object has been instantiated. However, if I am using a singleton to guarantee only one db connection, why not use the db connection resource link to do this? Here is the code I am using. (PS: it works fine). I use the comment to be able to search for my classes easily.
/*one*/
class one
{
public static $db;
private function __construct()
{
self::$db=new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
}
public static function get()
{
if(self::$db==NULL)
{
new self();
}
return self::$db;
}
}
In PHP, a constructor does not return.
So your
getmethod returns aoneobject, the first time it’s called, then amysqliobject. Probably not what you want.If you want to return the
mysqliobject, you do not need a singleton, as there is no need to create an instance of an object that’s only here to return an instance of another object.The registry pattern would be better in such a case.
If you need to provide methods (a wrapper for your DB object), then create a real singleton.
EDIT
I checked your updated code.
Now you return always the
mysqliinstance. But you do not need to instantiate your own object. That’s completely useless…If you really want to go with your kind of pattern, as golden said, in your static instance, checks if
self::dbisNULL. If yes, creates themysqliinstance, and assign it toself::db. Then returns it.Also set the constructor private, so users won’t be able to create useless instances of your class. Or better make it public and throw an exception: