如何简单地在PDO中返回对象? [英] How can I simply return objects in PDO?
本文介绍了如何简单地在PDO中返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一次尝试PDO.
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);
foreach($stmt as $animals)
{
echo $animals->name;
}
如果我跳过setFetchMode()
方法,那么我需要调用我不想要的$animals["name"]
.
If i skip the setFetchMode()
method, then I need to call $animals["name"]
which I do not want.
但是我不想为我执行的每个查询调用setFetchMode()
.
But I do not want to call the setFetchMode()
for each query I do.
是否可以设置默认的FetchMode?或其他一些方法使query()
返回具有一个全局设置的对象.
Is there a way to set the default FetchMode ? Or some other method to make the query()
return objects with one global setting.
推荐答案
也许您可以尝试扩展PDO类以自动为您调用该函数……简而言之:
Perhaps you could try extending the PDO class to automatically call the function for you... in brief:
class myPDO extends PDO
{
function animalQuery($sql)
{
$result = parent::query($sql);
$result->setFetchMode(PDO::FETCH_INTO, new animals);
return $result;
}
// // useful if you have different classes
// function vegetableQuery($sql)
// {
// $result = parent::query($sql);
// $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
// return $result;
// }
}
$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);
$stmt = $dbh->animalQuery("SELECT * FROM animals");
foreach($stmt as $animals)
{
echo $animals->name;
}
这篇关于如何简单地在PDO中返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文