如何将数据库连接传递给另一个类? [英] How to pass DB connection to another class?

查看:215
本文介绍了如何将数据库连接传递给另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正尝试通过以下方式传递数据库连接:

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>';
    }
}

但是我得到:致命错误:在非对象上调用成员函数prepare().我在做什么错了?

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

推荐答案

您已经正确地将db-to-class-constructor部分传递了.

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

但这不是您编码方式的有效类定义.您需要将这些代码行(在// execute some query之后)放入一个函数中.代码行不能放在它们所在的位置,而是在User类内部而不是在函数内部浮动.这不是合法的PHP.

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.

在每次调用prepare()或execute()之后,您还应该检查错误状态.如果出现错误(例如SQL语法错误或表不存在等),它们将返回FALSE.

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>';
        }
    }
}

这篇关于如何将数据库连接传递给另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆