Instantiate an object without calling its construc

2019-06-14 22:29发布

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.

4条回答
贼婆χ
2楼-- · 2019-06-14 23:07

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.

查看更多
Emotional °昔
3楼-- · 2019-06-14 23:09

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
查看更多
forever°为你锁心
4楼-- · 2019-06-14 23:16

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

查看更多
该账号已被封号
5楼-- · 2019-06-14 23:16

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

查看更多
登录 后发表回答