To restore the state of an object which has been persisted, I'd like to create an empty instance of the class, without calling its constructor, to later set the properties with Reflection.
The only way I found, which is the way Doctrine does, is to create a fake serialization of the object, and to unserialize()
it:
function prototype($class)
{
$serialized = sprintf('O:%u:"%s":0:{}', strlen($class), $class);
return unserialize($serialized);
}
Is there another, less hacky way, to do that?
I was expecting to find such a way in Reflection, but I did not.
No. At least not w/o redefining a class'es codebase by using extensions like runkit.
There is no function in PHP Reflection that would allow you to instantiate a new object w/o calling the constructor.
That is most certainly not possible for two reasons:
Everything else will mean more work, more implementation and more code - so most probably more hacky in your words.
Another way will be to create a child of that class with and empty constructor
and then to use the Child type:
Update: ReflectionClass::newInstanceWithoutConstructor is available since PHP 5.4!
By definition, instantiating an object includes callings its constructor. Are you sure you wouldn't rather write more lightweight constructors? (And no, I don't think there's another way.)