【发布时间】:2012-05-03 18:19:12
【问题描述】:
我有一个想要成为单例的 Db 访问类。 但是,我不断收到此错误:
Accessing static property Db::$connection as non static
in /srv/www/htdocs/db_mysql.php on line 41"
(line 41 is marked below)
代码如下:
Class Db {
// debug mode
var $debug_mode = false;
//Hostname - localhost
var $hostname = "localhost";
//Database name
var $database = "db_name";
//Database Username
var $username = "db_user";
//Database Password
var $password = "db_pwd";
private static $instance;
//connection instance
private static $connection;
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Db;
self::$instance->connect();
} //!self::$instance
return self::$instance;
} // function getInstance()
/*
* Connect to the database
*/
private function connect() {
if (is_null($this->hostname))
$this->throwError("DB Host is not set,");
if (is_null($this->database))
$this->throwError("Database is not set.");
$this->connection = @mysql_connect($this->hostname, $this->username, $this->password); // This is line 41
if ($this->connection === FALSE)
$this->throwError("We could not connect to the database.");
if (!mysql_select_db($this->database, $this->connection))
$this->throwError("We could not select the database provided.");
} // function connect()
// other functions located here...
} // Class Db
似乎在 getInstance() 函数中检查静态变量 $instance 失败。我该如何解决这个问题?
【问题讨论】:
-
为什么
$connection需要是静态的?你应该可以把它变成一个普通的成员变量,因为无论如何这个东西只会有一个实例。
标签: php database class singleton