2017-05-26 13 views
-1

なぜ私はこのエラーが発生しているのか分かりませんし、5時間修正する方法に苦労しています。 未定義のプロパティ:MySQLDatabase :: $ DB_CONFIG

class MySQLDatabase { 
    function __construct(){ 
if(file_exists(ROOT_PATH.'config.php')){ 
     $db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true); 
     $this->open_connection(db_config); 
}} 

function open_connection() { 
    $this->connection = mysqli_connect(
      $this->db_config['DBLocation'], 
      $this->db_config['DBName'], 
      $this->db_config['DBPassword'], 
      $this->db_config['DBUsername'] 
    ); 

    if(mysqli_connect_errno()) { 
     echo "Connection failed: " . mysqli_connect_error(); 
    } 
} 
+0

は、クラス内でこのコードですか? –

+0

'$ this-> open_connection(db_config);' 'db_config'には' $ '記号がありません。 –

+0

'open_connection()'には署名がありません。 –

答えて

3

$db_configだけそれがで定義されています方法に存在する変数である$this->db_configはクラスのいずれかの方法で参照することができる全く別の変数です。あなたのコンストラクタで

は、$this->db_config代わりの$db_configを設定します。

$this->db_config = json_decode(...); 

それからちょうど引数なしopenメソッドを呼び出します:openメソッドは、クラスで定義されています$this->dbconfigを参照しているので

$this->open_connection(); 

レベルでは、パラメータとして渡す必要はありません。コメントを

+0

ありがとう、私はこれと5時間苦労してきました。 –

+0

私はちょうど私が関数内でクラスをアクティブにすることができる方法はありますか?私は、オブジェクト指向のPHPを使用して私の関数内に2つのテーブルを作成するクエリを開始する必要がありますが、私はどのように考えていない..私はクラスDatabaseQueryを作成し、そこにクエリを置くが、 –

1

適切なコード:

class MySQLDatabase { 
    // define class property 
    protected $db_config; 

    function __construct(){ 
     if(file_exists(ROOT_PATH.'config.php')){ 
      // set property value as a result of `json_decode` 
      $this->db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true); 
      // json_decode can fail to return correct json 
      // if your file is empty or has some bad contents 
      // so we check if we really have a proper array 
      if (is_array($this->db_config)) { 
       // no need to pass argument to a function 
       // as `db_config` property is already set 
       $this->open_connection(); 
      } 
     } 
    } 

    function open_connection() { 
     $this->connection = mysqli_connect(
      $this->db_config['DBLocation'], 
      $this->db_config['DBName'], 
      $this->db_config['DBPassword'], 
      $this->db_config['DBUsername'] 
     ); 

     if(mysqli_connect_errno()) { 
      echo "Connection failed: " . mysqli_connect_error(); 
     } 
    } 
関連する問題