可以在类之间维护PDO连接吗?

Ale*_*lan 6 php mysql oop pdo

我正在尝试创建一个简单的查询库,我正在使用PDO进行数据库访问.

假设我有以下两个类:

class FirstClass {
    var $dbh;

    function __construct($host,$dbname,$user,$pw) {
        $this->dbh = new PDO ("mysql:host=$host;dbname=$dbname",$user,$pw);
    }

    function use_second($foo) {
        return new SecondClass ($foo,$this->dbh);
    }
}

class SecondClass {
    function __construct($foo, $dbh) {
        $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
        $sth = $sth->execute(array('foo'=>$foo));
        // do something with the query
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在类之间使用相同PDO连接的正确方法吗?- 因为我似乎遇到了一些问题,例如,如果我var_dump是第二堂课的连接,我得到:

object(PDO)#2 (0) { }
Run Code Online (Sandbox Code Playgroud)

当然那不对?

此外,如果我运行一个选择查询,然后转储该$sth变量,我只是得到:

bool(true)
Run Code Online (Sandbox Code Playgroud)

这是因为我错误地处理了连接吗? - 如果是这样,我怎样才能在类之间正确使用相同的连接?

Tad*_*eck 3

发生这种情况是因为您覆盖了$sth,这是您的语句,但现在是一个布尔值:

class SecondClass {
    function __construct($foo, $dbh) {
        // returns PDOStatement:
        $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
        // returns boolean:
        $sth = $sth->execute(array('foo'=>$foo));
        // do something with the query
    }
}
Run Code Online (Sandbox Code Playgroud)

要纠正它,只需不要覆盖$sth,这样您就可以从中获取结果:

class SecondClass {
    function __construct($foo, $dbh) {
        // returns PDOStatement:
        $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
        // returns boolean:
        $success = $sth->execute(array('foo'=>$foo));
        // do something with the query
        if ($success) {
            // do something with $sth->fetchAll() or $sth->fetch(), or anything
            $all_the_results = $sth->fetchAll();
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是唯一一个*实际上*解释了这个问题的答案 - 谢谢 (3认同)