问题
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):
$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.
How can I accomplish the desired effect using PDO?
回答1:
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');
Alternatively, create an instance and fetch into it (i.e. set fetch mode to PDO::FETCH_INTO
).
来源:https://stackoverflow.com/questions/8898794/using-pdofetch-class-with-magic-methods