【问题标题】:Db singleton class failingDb 单例类失败
【发布时间】: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


【解决方案1】:

您已将 $connection 标记为静态:

private static $connection;

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

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

这就是你得到错误的原因。你应该像使用self一样访问它

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

或从声明 $connection 中删除 static

private $connection;

顺便说一句:就在这条线的下方,你又是$this->connection === FALSE,又是if (!mysql_select_db($this->database, $this->connection))

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多