2012-05-03 104 views
0

私はシングルトンになりたいDbアクセスクラスを持っています。 しかし、私はこのエラーを取得しておいてください。ここでは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()関数内の静的変数$インスタンスのチェックが失敗しているようです。これをどうすれば解決できますか?

+0

なぜ '$ connection'は静的である必要がありますか?とにかくこの事例は1つしかないので、それを通常のメンバ変数にすることができます。 –

答えて

1

を使用している:

private static $connection;

あなたが$thisを使用してアクセスしてみてくださいしかし:

$this->connection = ...(ライン41)

となっているので、エラーが発生します。

private $connection;

ところで:あなたはself

self::$connection = ...(補正ライン41)を使用してのようにアクセスする必要があり

OR宣言$connectionからstaticを削除するだけで、この行の下に、あなたは再び再び$this->connection === FALSEと中を持っていますif (!mysql_select_db($this->database, $this->connection))

1

あなたはstaticとして$connectionをdecalredいる$this->connectionではなくself::$connection

関連する問題