Db单身类失败

时间:2012-05-03 18:19:13

标签: php database class singleton

我有一个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是否失败。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您使用的是$this->connection而不是self::$connection

答案 1 :(得分:1)

您已将$connection标记为静态:

private static $connection;

但是您尝试使用$this访问它:

$this->connection = ...(第41行)

这就是你得到错误的原因。您应该像使用self

一样访问它

self::$connection = ...(更正第41行)

或从声明static中移除$connection

private $connection;

顺便说一句:就在这一行的下方,您再次$this->connection === FALSE再次在if (!mysql_select_db($this->database, $this->connection))

相关问题