我想使用PDO的FETCH_INTO使用构造函数填充类:
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工作正常.
FETCH_INTO有什么问题?
您的代码中有两个错误:
1)你忘了$q-> fetch()
... $q->execute(array($id)); $q->fetch(); // This line is required
2)但是即使在添加$q-> fetch()之后你也会得到这个:
Fatal error: Cannot access private
property User::$name in …
因此,正如您所看到的,即使在类方法中调用PDO,PDO也无法访问私有成员.
这是我的解决方案:
... $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; }