Gajus Gajus - 1 month ago 18
PHP Question

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

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

<?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']);


Alternatively, one could use
PDO::FETCH_PROPS_LATE
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

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