0

我有一个我想成为单身人士的 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 失败了。我怎样才能解决这个问题?

4

2 回答 2

1

你正在使用$this->connection而不是self::$connection

于 2012-05-03T18:21:44.563 回答
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))

于 2012-05-03T18:22:43.897 回答