Instantiate an object without calling its constructor in PHP

Benjamin picture Benjamin · Aug 4, 2011 · Viewed 10.3k times · Source

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.

Answer

Benjamin picture Benjamin · Sep 7, 2011

Update: ReflectionClass::newInstanceWithoutConstructor is available since PHP 5.4!