Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate an object without calling its constructor in PHP

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.

like image 604
BenMorel Avatar asked Aug 04 '11 16:08

BenMorel


People also ask

Can you instantiate an object without a constructor?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

Can we override constructor in PHP?

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.

Is constructor mandatory in PHP?

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.

Which function is used to initialize the object automatically in PHP?

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.


1 Answers

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

like image 57
2 revs Avatar answered Oct 14 '22 08:10

2 revs