This is the singleton pattern also named as the singleton class. Its goal is to allow only one object of type singleton. If there is already one and I call it, I’d like it to error out in some way. This won’t happen in production but in development. Is there a better way then just saying echo echo “Error:only one connection”;
class singleton
{
protected static $_db_pointer = NULL;
private function __construct()
{
$this->_db_pointer = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_DATABASE);
}
public static function get_instance()
{
if(self::$_db_pointer == NULL)
{
return new self();
}
else
{
echo "Error:only one connection";
}
}
}
Exceptions usually are better.
You can also use “LogicException”, “RuntimeException”, and a few others.
Further reading:
http://www.php.net/manual/en/language.exceptions.php
Another approach with singleton class is just to return the object instead of creating a new instance if one exists.