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 に答える