我修改了您的课程以使其按您的预期工作:
<?php
class Database
{
var $conn = null;
var $config = array(
'username' => 'someuser',
'password' => 'somepassword',
'hostname' => 'some_remote_host',
'database' => 'a_database'
);
function __construct() {
$this->connect();
}
function connect() {
if (is_null($this->conn)) {
$db = $this->config;
$this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
if(!$this->conn) {
die("Cannot connect to database server");
}
if(!mysql_select_db($db['database'])) {
die("Cannot select database");
}
}
return $this->conn;
}
}
用法:
$db = new Database();
$conn = $db->connect();
请注意,您可以根据需要多次调用 connect() ,它将使用当前连接,或者如果它不存在则创建一个。这是一件好事。
另外,请注意,每次实例化数据库对象(使用 new)时,您都将创建与数据库的新连接。我建议您考虑将 Database 类实现为Singleton或将其存储在Registry中以进行全局访问。
你也可以用肮脏的方式来做,然后把它塞进 $GLOBALS。
编辑
我冒昧地修改了您的类以实现单例模式,并遵循 PHP5 OOP 约定。
<?php
class Database
{
protected static $_instance = null;
protected $_conn = null;
protected $_config = array(
'username' => 'someuser',
'password' => 'somepassword',
'hostname' => 'some_remote_host',
'database' => 'a_database'
);
protected function __construct() {
}
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getConnection() {
if (is_null($this->_conn)) {
$db = $this->_config;
$this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
if(!$this->_conn) {
die("Cannot connect to database server");
}
if(!mysql_select_db($db['database'])) {
die("Cannot select database");
}
}
return $this->_conn;
}
public function query($query) {
$conn = $this->getConnection();
return mysql_query($query, $conn);
}
}
用法:
$res = Database::getInstance()->query("SELECT * FROM foo;");
或者
$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");