Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 类之间是否可以保持PDO连接?_Php_Mysql_Oop_Pdo - Fatal编程技术网

Php 类之间是否可以保持PDO连接?

Php 类之间是否可以保持PDO连接?,php,mysql,oop,pdo,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) { r

我试图创建一个简单的查询库,并使用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
    }
}
这是在类之间使用相同PDO连接的正确方法吗?-因为我似乎对此有一些问题,例如,如果我
var\u dump
我从第二个类的连接,我会得到:

object(PDO)#2 (0) { }
这肯定不对吗

另外,如果我运行select查询,然后转储
$sth
变量,我只会得到:

bool(true)

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

请查看文档以了解更多信息。它返回一个布尔值。
sth
true
结束这一事实意味着查询成功


您的设计有点不稳定,因为您正在使用其他对象的非工厂方法创建对象,这可能会令人困惑。理想情况下,所有对象都将在控制器执行开始时创建,并注入到需要它们的其他对象中(例如,
PDO
对象将在
FirstClass::u构造
之外创建,并且您将拥有类似于
的构造(PDO$db)
相反。

在您的情况下,我只需询问(我的意思是询问是否设置了prequist)ready PDO对象

function __construct($dbh) {
    $this->dbh = $dbh;
}
这样,您就可以更清楚地了解对象需要什么(它不需要用户/密码等,它需要数据库连接!)


它还消除了对抽象类(FirstClass)的需要,因为您可以直接转到第二个类。

发生这种情况,因为您覆盖了
$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
    }
}
要更正它,只需不要覆盖
$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();
        };
    }
}

回答标题中的问题:是的,他们可以。是的,因为你可以。你可以在提问之前先尝试一下,这样可以节省你和我们的时间。嗯……我在问题中提到,我尝试过这个。我说我不相信它工作正常,我想知道我对连接的处理是否是导致它的唯一原因y一个真正解释了这个问题的人-thanks@AlexCoplan:谢谢,我很高兴我帮了忙:)