使用 PDO::FETCH_CLASS 和魔术方法

2021-12-26 00:00:00 magic-methods php pdo

我有一个使用魔法方法来存储属性的类.这是一个简化的例子:

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).

相关文章