Creating an Instance of an Object without Calling Its Constructor in PHP


Today, I stumbled upon an article in a local PHP developers group. It was about creating an instance of an object without calling its constructor (as mentioned in post title).

At first, the idea made no sense to me. Because, constructor method is run every time an object is instantiated, this property is the whole point of writing a constructor. Out of curiosity, I started reading the article. As it turns out, it is really beneficial for testing and mocking purposes. The more interesting thing is the method used to achieve this is simply brilliant.

The trick which originally occurs in PHPUnit source code is as follows:

$object = unserialize(
    sprintf('O:%d:"%s":0:{}', strlen($className), $className)
);

As of PHP 5.4, there is a built-in method for this in ReflectionClass:

$reflection = new ReflectionClass($className);
$object = $reflection->newInstanceWithoutConstructor();