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.
You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.
In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature. Their parameters can be changed freely and without consequence.
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one. Save this answer.
PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
Update: ReflectionClass::newInstanceWithoutConstructor is available since PHP 5.4!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With