2017-06-09 6 views
0

問題が発生していて、なぜ動作していないのかわかりません。それはおそらく単純です。PHPがPDOオブジェクトをクラスに渡す

私は、同じファイル内のクラスにPDOオブジェクトを渡していると私はPDOオブジェクトがクエリを実行することを使用しようとしていますが、私はここで、次のエラー

Fatal error: Call to a member function prepare() on null

は、私が思う私のコードで取得それはタイプミスでエラー

答えて

1

を引き起こしているもの

try{ 
    $pdo = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPASS); 
} 
catch (PDOexception $e) { 
    // get the error message 
    $message = 'Connection failed: ' . $e->getMessage(); 
} 

$test= new Test($pdo); 

var_dump($test->get_users()); 

class Test{ 

    private $pdo; 

    public function __contruct($pdo) { 
     $this->pdo = $pdo; 
    } 

    public function get_users() { 

     $sql = "SELECT 
        user.*, 
        user_role.role AS role 
       FROM user 
        LEFT JOIN user_role ON 
         user.role_id = user_role.id;"; 

     $stmt = $this->pdo->prepare($sql); 
     $stmt->execute(); 

     $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 
    } 
} 

任意のアイデアを動作するはずです、あなたは__contruct代わりに__constructを入力しました。行方不明のsがありました。

+0

はい、Tobiasが正しいです!私はまた、コード補完と型安全性を向上させるために、 '__construct(PDO $ pdo)'のようにPDOオブジェクトにコンストラクタをヒントします。 – Stoffo

+0

あなたが見ていないほど多くのエラーを見るほど、 –

関連する問題