I have multiple scripts referring to one another and it is getting a little confusing with database calls. I stumbled upon the singleton method, and I am trying to use it to create a Database class that will make sure there is only one connection at a time.
This is what I have:
class Database{
//Store the single instance of Database
private static $m_pInstance;
private function __construct(){
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
}
public static function getInstance()
{
if(!self::$m_pInstance)
{
self::$m_pInstance = new Database();
}
return self::$m_pInstance;
}
}
My connection definitions are stored in a cfg.php file which is required by this script. For the most part I understand how this works, but not well enough to understand why it isn't working. Here is the reference to this database:
$mysqli = Database::getInstance();
Can someone help me figure out what I am doing wrong? The connection fails when I run it. It works when I put the above reference into a comment and simply connect with this:
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Thanks.