Instantiate an object without calling its constructor in PHP

Related searches

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!

ReflectionClass::newInstanceWithoutConstructor - Manual, Creating an Instance of an Object without Calling Its Constructor in PHP Today, I stumbled upon an article in a local PHP developers group. Because, constructor method is run every time an object is instantiated, this� Today, I stumbled upon an article in a local PHP developers group. It was about creating an instance of an object without calling its constructor (as mentioned in post title). At first, the idea made no sense to me. Because, constructor method is run every time an object is instantiated, this property is the whole point of writing a constructor.

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

Creating an Instance of an Object without Calling Its Constructor in , Creating objects without __construct() in PHP 5.0, 5.1, 5.2, 5.3 and later. <?php Paranormal instantiation. without invoking its constructor. In C#, is there a way to instantiate an instance of a class without invoking its constructor? Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it’s possible using some kind of C# hackery.

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.)

Have fun with PHP: how to bypass an object constructor, star2: Instantiate PHP objects without constructors calls - Ocramius/Instantiator. a way of avoiding usage of constructors when instantiating PHP classes. Another way to overcome PHP's lack of multi constructors support is to check for the constructor's parameters' type and variate the operation accordingly. This works well when the number of parameters stays the same in all your constructors' needs.

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:

  1. Objects are either serializeable or not and
  2. 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.

Ocramius/Instantiator: :star2: Instantiate PHP objects without , In this blog post we will look at how you could create an instance of an object in C# without calling its constructor – which sounds a bit crazy, but� Instantiating an object means that we create a new object of a class in PHP. Before you can create an object, you must create a class. The class is the overall blueprint or template of the object. So you must first have a class. Then once you have a class, you can create an object of a class. So let's say we create a class named vehicles. Vehicles is the overall blueprint or template. Inside of this vehicles class, we can create an object or several objects.

Doctrine has a package for this which you can use: https://github.com/doctrine/instantiator

Instantiating an object without using its constructor in C#, By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose: <?php $genericObject = new stdClass(); ?> I had the most difficult time finding this, hopefully it will help someone else!

Object initializers allow assigning values to any accessible properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. The object initializer syntax enables to specify arguments for a constructor or omit the arguments (and parentheses syntax).

A ReflectionException if the class is an internal class that cannot be instantiated without invoking the constructor. In PHP 5.6.0 onwards, this exception is limited only to internal classes that are final.

The relatively unknown API is called FormatterServices.GetUninitializedObject and it will allocate an object without running any initalization code, including the instance constructor. The object is completely uninitialized, which also means that, for example, members would not be initialized to their values.

Comments
  • possible duplicate of How does Doctrine 2 retrieve entities without calling the entity's constructor?
  • @hakre: no, that question only raises the question of serialization, not the alternatives.
  • Which alternatives? And what is "less hacky"? - Btw: StdClass objects don't have a constructor, so theirs is not called anyway.
  • Which alternatives: that is the question I'm asking: what are the alternatives, if any? See my personal definition for "less hacky" in the comments below your answer.
  • @Petah: do you have any source for this? AFAIK, PHP 5.4.0 is not a RC, therefore it is considered "production ready" by the PHP team. That said, it looks like some distributions such as Debian do not consider it "production ready" yet for some reason.
  • yes it might be theoretically production ready, but I say its not because no major distros, or hosting providers offer it. Also there will no doubt be a lot of bugs that surface after the initial release. Hence why I think 5.4.3 will be the golden version where major websites and providers adopt it.
  • What do you do if the child class needs actually parameters in it's constructor and the constructor to be called?
  • @hakre you can provide as many actual parameters as you want. But that is not the use case that Benjamin was talking about. He wants to make a prototype of the Parent class without setting any properties when instantiating the class - the properties will be latter set by Reflection. The doctrine2 for example needs that because it has no control of how a Entity __constructor will look like - it's implementation is in the user hands - but it knows how the properties look like because they are mapped with metadata (annotations, xml, yml, etc)
  • @catalin.costache: while not fulfilling the original requirement, your solution is interesting and reminds me of how Doctrine creates proxies for related user class instances. It's quite strange that they didn't choose that solution for the retrieved base instances, actually! Looks like it would've been more consistent to me - that's just an opinion without yet a great deal of thinking coming with it, that said :-)
  • I'm not entirely sure if the OP really has the option to override the constructor by object refinement/inheritance.
  • hakre: what do you mean? The doc explicitly states that "unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has."
  • I could of course make other design choices, but they all have their side effects; that's why I'm looking for a generic way.
  • Do you mean temporarily renaming the constructor?
  • What I consider "hacky" is to hand-write a serialized string. If PHP's serialization method changes, the code is broken. What surprises me with Reflection, is that it provides ways to instantiate classes with constructor, to dynamically set properties, but not to instantiate without constructor. They look like 2 differents things to me: either you instantiate with the constructor, in which case you don't need Reflection, and you do the things the "normal" way, without it; or you use Reflection, to do some "magic" on the instance; why not creating an empty instance to work with then?