How to pass DB connection to another class?

∥☆過路亽.° 提交于 2019-12-24 06:36:08

问题


I'm currently trying to pass a DB connection as follows:

class Test {
    public $user;
    public $db;

    function __construct() {
        // connect to database
        try {
            $this->db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $err) {
            die($err->getMessage());
        }
        $this->user = new User($this->db);
    }
}

class User {
    public $db;

    function __construct($db) {
        $this->db = $db;
    }

    // execute some query
    $sql = "SELECT * FROM test";
    $sth = $this->db->prepare($sql);
    $sth->execute();
    $result = $sth->fetch();
    if(!empty($result)) {
        echo '<pre>';
        var_dump($result);
        echo '</pre>';
    }
}

But I get: Fatal error: Call to a member function prepare() on a non-object. What am I doing wrong?


回答1:


You've got the passing-db-to-class-constructor part correct.

But this is not a valid class definition the way you've coded it. You need to put those lines of code (following // execute some query) into a function. Lines of code can't live where they are, floating around inside the User class but not inside a function. It's not legal PHP.

You should also check for error status after each call to prepare() or execute(). They return FALSE if there's an error, like an SQL syntax error, or the table doesn't exist, etc.

class User {
    public $db;

    function __construct($db) {
        if (! $db instanceof PDO) { die("What are you trying to pull anyway?"); }
        $this->db = $db;
    }

    function doSomething() {
        // execute some query
        $sql = "SELECT * FROM test";
        $sth = $this->db->prepare($sql);
        if ($sth === false) {
            die(print_r($this->db->errorInfo(), true));
        }
        $status = $sth->execute();
        if ($status === false) {
            die(print_r($sth->errorInfo(), true));
        }
        $result = $sth->fetch();
        if(!empty($result)) {
            echo '<pre>';
            var_dump($result);
            echo '</pre>';
        }
    }
}


来源:https://stackoverflow.com/questions/13793165/how-to-pass-db-connection-to-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!