本文介绍了PDO的FETCH_INTO $此类不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用PDO的FETCH_INTO
用构造函数填充类:
I want to populate class with constructor using FETCH_INTO
of PDO:
class user
{
private $db;
private $name;
function __construct($id)
{
$this->db = ...;
$q = $this->db->prepare("SELECT name FROM users WHERE id = ?");
$q->setFetchMode(PDO::FETCH_INTO, $this);
$q->execute(array($id));
echo $this->name;
}
}
这不起作用.没错,没事.脚本没有错误,FETCH_ASSOC
正常运行.
This does not work. No error, just nothing. Script has no errors, FETCH_ASSOC
works fine.
FETCH_INTO
怎么了?
推荐答案
您的代码中有两个错误:
You have two errors in your code:
1)您忘记了$ q-> fetch()
1) You forgot $q->fetch()
...
$q->execute(array($id));
$q->fetch(); // This line is required
2)但是即使添加$ q-> fetch()后,您仍然会得到:
2) But even after adding $q->fetch() you'll get this:
因此,如您所见,即使在类方法内部被调用,PDO也无法访问私有成员.
So, as you can see, PDO cannot access private members even if it is called inside class method.
这是我的解决方案:
...
$q->execute(array($id));
$q->setFetchMode(PDO::FETCH_ASSOC);
$data = $q->fetch();
foreach ($data as $propName => $propValue)
{
// here you can add check if class property exists if you don't want to
// add another properties with public visibility
$this->{$propName} = $propValue;
}
这篇关于PDO的FETCH_INTO $此类不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!