2016-07-29 2 views
2

私はMysqliDb https://github.com/joshcam/PHP-MySQLi-Database-Classを持っています。私のPHPクラスの既に他のクラスからmysqliDb接続を作成しました

<?php 
require_once ('MysqliDb.php'); 

class Main{ 

protected $db; 


public function __construct() 
{ 
    $this->db = new MysqliDb ('localhost', 'root', 'tuncay', 'db'); 
} 

} 

Class A extends Main{ 

public function __construct() 
{ 
    $this->db = MysqliDb::getInstance(); 
    echo $this->db->where("id", 5)->getOne('test')['text']; 
} 

} 

$a = new A(); 

?> 

PHPのエラー:致命的なエラー:行に/.../db/index.phpにヌルに()メンバ関数を呼び出して21 ここで()関数はMysqliDb.phpに属します

どうしたのですか?メインクラスから$ this-> dbを取得しました

DB接続をAクラスにしておきたいだけです。

+0

hmm ...前にクラスのメインをinstatiatedしていない場合、保持するDB接続はありません!たぶんあなたは 'parent :: _ construct()'をしたいでしょうか? – Jeff

答えて

2

あなたのクラスAは、親の__constructを置き換えます。そして、あなたは、私はこのように行うことができます意味

Class A extends Main{ 
    public function __construct() 
    { 
    parent::__construct(); 
    $this->db = MysqliDb::getInstance(); 
    echo $this->db->where("id", 5)->getOne('test')['text']; 
    } 
    ... 
} 
+0

この行 '$ this-> db = MysqliDb :: getInstance();'は意味をなさないか、必要ではありません。 – Jeff

+0

クラスでは、Mainクラスにある$ this-> dbを使いたいだけです。 parent :: _ constructを使用すると、接続は再び繰り返されます。それは普通ですか? – tuncayeco

+0

あなたの子コンストラクトはあなたの親コンストラクトを置き換え、 '$ this-> db = new MysqliDb( 'localhost'、 'root'、 'tuncay'、 'db');' dont uses。 'parent :: __ construct()'を追加すると、それが使用されます。 – Vladimir

1

を追加してみてください。

<?php 
require_once ('MysqliDb.php'); 

class Main{ 

    protected $db; 

    public function connectDB() 
    { 
    $this->db = new MysqliDb ('localhost', 'root', 'pass', 'db'); 
    } 
} 

Class A extends Main{ 
    public function __construct() 
    { 
    $this->connectDB(); 
    echo $this->db->where("id", 5)->getOne('test')['text']; 
    } 
} 

$a = new A(); 
?> 

することは、この正常ですか?私は、connectDB()関数を呼び出すたびにメモリにダメージを与えません。それとも毎回メモリの同じ部分を呼び出すのでしょうか?

関連する問題