This is indeed possible.
Modified from from PHPUnit_Framework_MockObject_Generator.php
1 $myClass = unserialize(
2 sprintf(
3 'O:%d:"%s":0:{}',
4 strlen('MyClass'), 'MyClass'
5 )
6 );
Please keep in mind, that code like this is all good and justified in a framework like PHPUnit. But if you have to have code like this in your production code, you are likely doing something very odd.
Since you asked for an explanation:
When you serialize an Object you get a string representation of the object. For instance
echo serialize(new StdClass) // gives O:8:"stdClass":0:{}
The O
means object. 8
is the string length of the class name. "stdClass"
is obviously the class name. The serialized object has 0
properties set (more to that later), indicated by the empty curly braces. The :
are just delimiters.
Every serialized string can be recreated into its original "live" value with the unserialize function. Doing so, will circumvent the constructor. Like Charles correctly pointed out the magic method __wakeup()
will be called if it is defined (just like __sleep()
will be called when serializing).
In Line 3 you see a string prepared to be used with sprintf (line 2). As you can see the string length of the class name is given as %d
and the class name is given as %s
. This is to tell sprintf that it should use the first argument passed to it in line 4 as a digit and the second as a string. Hence, the result of the sprintf call is
'O:7:"MyClass":0:{}'
You would replace both occurences of "MyClass" in line 4 with your desired class name to create a serialized string of the class you want to instantiate without invoking the controller.
This string is then unserialized into a MyClass instance in line 1, bypassing the constructor. The unserialized instance will have all the methods of it's class and also any properties. If there is properties in MyClass, these will have their default values, unless you add different values to the serialized dummy string.
And that's already it. Nothing too magical about it.