[英]Using PDO::FETCH_CLASS with Magic Methods
I have a class that uses magic methods to store properties. 我有一个使用魔术方法来存储属性的类。 Here is a simplified example: 这是一个简化的例子:
class Foo {
protected $props;
public function __construct(array $props = array()) {
$this->props = $props;
}
public function __get($prop) {
return $this->props[$prop];
}
public function __set($prop, $val) {
$this->props[$prop] = $val;
}
}
I'm trying to instantiate objects of this class for each database row of a PDOStatement
after it's executed, like this (doesn't work): 我试图在PDOStatement
执行后为每个数据库行实例化这个类的对象,就像这样(不起作用):
$st->setFetchMode(PDO::FETCH_CLASS, 'Foo');
foreach ($st as $row) {
var_dump($row);
}
The problem is that PDO::FETCH_CLASS
does not seem to trigger the magic __set()
method on my class when it's setting property values. 问题是PDO::FETCH_CLASS
在设置属性值时似乎没有在我的类上触发magic __set()
方法。
How can I accomplish the desired effect using PDO? 如何使用PDO实现所需效果?
The default behavior of PDO is to set the properties before invoking the constructor. PDO的默认行为是在调用构造函数之前设置属性。 Include PDO::FETCH_PROPS_LATE
in the bitmask when you set the fetch mode to set the properties after invoking the constructor, which will cause the __set
magic method to be called on undefined properties. 当您设置获取模式以在调用构造函数后设置属性时, PDO::FETCH_PROPS_LATE
掩码中包含PDO::FETCH_PROPS_LATE
,这将导致在未定义的属性上调用__set
魔术方法。
$st->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Foo');
Alternatively, create an instance and fetch into it (ie set fetch mode to PDO::FETCH_INTO
). 或者,创建一个实例并获取它( PDO::FETCH_INTO
获取模式设置为PDO::FETCH_INTO
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.