Gajus Gajus - 1 year ago 128
PHP Question

How does PDO::FETCH_CLASS populate the object properties before the constructor is called?

allows to initialise a class instance with pre-populated data. It looks something like this:

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;

->query("SELECT `foo`, `bar` FROM `qux`;")
->fetchAll(PDO::FETCH_CLASS, 'Bar', ['test']);

Alternatively, one could use
to call the constructor before the setter is triggered.

I am interested to know how does PDO manage to populate the Class instance through setters before the constructor is called, or more specifically, if there is a way to replicate this behaviour?

Answer Source

It is possible to do this in PHP 5.4+ using ReflectionClass::newInstanceWithoutConstructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download