Can somebody explain to me why the following code does not act "as expected" ?
define("DB_HOST", "localhost");
define("DB_USER", "test");
define("DB_PASS", "test");
define("DB_NAME", "test");
class DBConnection {
var $handle; // connection handle
function DBConnection() {
print "Creating new database connection\n";
$this->handle = @mysql_connect(DB_HOST, DB_USER, DB_PASS) or
die("Could not connect to database");
mysql_select_db(DB_NAME, $this->handle) or
die("Could not switch to database ".DB_NAME);
}
function &getInstance() {
static $dbConn;
print "DBConnection::getInstance\n";
if (is_null($dbConn))
$dbConn =& new DBConnection();
return $dbConn;
}
function getLink() {
return $this->handle;
}
}
// START HERE
$a = DBConnection::getInstance();
$b = DBConnection::getInstance();
if ($a === $b) {
echo '$a and $b reference the same object.' . "\n";
}
--------------------------------------------------------------------------------
When running this script, it prints out the following:
DBConnection::getInstance
Creating new database connection
DBConnection::getInstance
Creating new database connection
$a and $b reference the same object.
Why do I get the "Creating new database connection" message twice? Shouldn't the message be printed only once, because the second time I've already got an instance of DBConnection?
(It seems to run the constructor twice, which is bad, because I create my database connection in here).
I'm running PHP 4.1.2.