PDO::FETCH_CLASS
允许用预填充的数据初始化类实例。它看起来像这样:
<?php
class Bar {
private $data = [];
public function __construct ($is) {
// $is === 'test'
// $this->data === ['foo' => 1, 'bar' => 1]
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$db
->query("SELECT `foo`, `bar` FROM `qux`;")
->fetchAll(PDO::FETCH_CLASS, 'Bar', ['test']);
或者,可以使用PDO::FETCH_PROPS_LATE
在触发setter之前调用构造函数。
我有兴趣知道PDO如何通过调用构造函数之前的setter来填充类实例,或者更具体地说,如果有一种方法来复制这种行为?
可以在PHP 5.4+中使用ReflectionClass::newInstanceWithoutConstructor来实现。
我这样做了:
我在超类
中声明了这个魔法方法 public function __set($name, $value) {
$method = 'set' . str_replace('_', '', $name); //If the properties have '_' and method not
if (method_exists($this, $method)) {
$val = call_user_func(array($this, $method), $value);
}
}