Db clase singleton fallando

I have a Db access class that I want to be a singleton. However, I keep getting this error:

Accessing static property Db::$connection as non static  
    in /srv/www/htdocs/db_mysql.php on line 41"    
(line 41 is marked below)

Aquí está el código:

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
    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

It seems that the check for the static variable $instance in the getInstance() function is failing. How can I fix this?

preguntado el 03 de mayo de 12 a las 19:05

Por que $connection need to be static? You should be able to make it a regular member variable since there will only be one instance of this thing anyways. -

2 Respuestas

you have decalred $connection como estático:

private static $connection;

however you try to access it using $this:

$this->connection = ... ( line 41)

and that is why you get an error. you should access it like using self

self::$connection = ... ( corrected line 41 )

O eliminar static from declaration $connection:

private $connection;

BTW: just below this line you have again $this->connection === FALSE Y de nuevo en if (!mysql_select_db($this->database, $this->connection))

contestado el 03 de mayo de 12 a las 19:05

Estas usando $this->connection más bien que self::$connection

contestado el 03 de mayo de 12 a las 19:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.