通过魔术方法使用PDO :: FETCH_CLASS [英] 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;
}
}
我正在尝试为PDOStatement
的每个数据库行实例化此类的对象,如下所示(无效):
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):
$st->setFetchMode(PDO::FETCH_CLASS, 'Foo');
foreach ($st as $row) {
var_dump($row);
}
问题在于,PDO::FETCH_CLASS
似乎在设置属性值时不会触发类上的魔术__set()
方法.
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实现所需的效果?
推荐答案
PDO的默认行为是在调用构造函数之前先设置属性.设置构造函数后,设置获取方式来设置属性时,在位掩码中包含PDO::FETCH_PROPS_LATE
,这将导致在未定义属性上调用__set
魔术方法.
The default behavior of PDO is to set the properties before invoking the constructor. 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.
$st->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Foo');
或者,创建一个实例并提取到其中(即,将提取模式设置为PDO::FETCH_INTO
).
Alternatively, create an instance and fetch into it (i.e. set fetch mode to PDO::FETCH_INTO
).
这篇关于通过魔术方法使用PDO :: FETCH_CLASS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!