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.
Update: ReflectionClass::newInstanceWithoutConstructor is available since PHP 5.4!
Another way will be to create a child of that class with and empty constructor
class Parent {
protected $property;
public function __construct($arg) {
$this->property = $arg;
}
}
class Child extends Parent {
public function __construct() {
//no parent::__construct($arg) call here
}
}
and then to use the Child type:
$child = new Child();
//set properties with reflection for child and use it as a Parent type
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.)
Is there another [...] way to do that?
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.
less hacky way
That is most certainly not possible for two reasons:
- Objects are either serializeable or not and
- serialize/unserialize is PHP's most native implementation of object persistence around
Everything else will mean more work, more implementation and more code - so most probably more hacky in your words.