Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PDOStatement::fetchObject set properties before the class is constructed?

Tags:

php

When I call this function, and add a constructor to my class, all my class properties are already set. How is that possible -- I thought you had to construct a class before you could set its properties?

like image 819
mpen Avatar asked Dec 03 '25 06:12

mpen


1 Answers

I guess that PDO uses some internal code to create an object without invoking the constructor. However it is possible to instance a new object without calling the constructor even in pure PHP, all you have to do is to deserialize an empty object:

class SampleClass {
    private $fld = 'fldValue';

    public function __construct() {
        var_dump(__METHOD__);
    }

    // getters & setters
}

$sc = unserialize(sprintf('O:%d:"%s":0:{}', strlen('SampleClass'), 'SampleClass'));
echo $sc->getFld(); // outputs: fldValue, without calling the construcotr

As of PHP 5.4.0+ ReflectionClass::newInstanceWithoutConstructor() method is available in reflection API.

like image 80
Crozin Avatar answered Dec 05 '25 20:12

Crozin