Instantiate an object without calling its constructor in PHP

我们两清 提交于 2019-12-08 14:38:14

问题


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.


回答1:


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




回答2:


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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/6944946/instantiate-an-object-without-calling-its-constructor-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!