我修改你的類工作,因爲你似乎是它期待:
<?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()多次,只要你喜歡,它將使用當前連接,或者創建一個,如果它不存在。這是好東西。
此外,請注意,每次您將實例化爲數據庫對象(使用新的)時,您將創建一個到數據庫的新連接。我建議你考慮實現你的數據庫類作爲Singleton或將它存儲在Registry以供全局訪問。
你也可以用骯髒的方式做到這一點,並將它推到$ GLOBALS中。
編輯
我把修改你的類實現Singleton模式,並按照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");
如果你有mysql。襪子問題,你可能想檢查這個問題的答案:http://stackoverflow.com/questions/1005485/warning-mysqlconnect-cant-connect-to-local-mysql-server – rojoca 2009-07-29 21:10:05