在PHP中实例化一个对象而不调用它的构造函数


Instantiate an object without calling its constructor in PHP

要恢复持久化对象的状态,我想创建一个类的空实例,而不调用其构造函数,以便稍后使用Reflection设置属性。

我发现的唯一方法,也是Doctrine的方法,就是创建对象的伪序列化,并将其unserialize():

function prototype($class)
{
    $serialized = sprintf('O:%u:"%s":0:{}', strlen($class), $class);
    return unserialize($serialized);
}

是否有另一种更不方法来做到这一点?

我期望在Reflection中找到这样的方法,但是我没有。

更新: ReflectionClass::newInstanceWithoutConstructor自PHP 5.4起可用!

另一种方法是使用空构造函数创建该类的子类

class Parent {
  protected $property;
  public function __construct($arg) {
   $this->property = $arg;
  }
}
class Child extends Parent {
  public function __construct() {
    //no parent::__construct($arg) call here
  }
}

,然后使用子类型:

$child = new Child();
//set properties with reflection for child and use it as a Parent type

根据定义,实例化对象包括调用其构造函数。您确定不想编写更轻量级的构造函数吗?(不,我不认为还有别的办法。)

是否有另一个[…]怎么做呢?

。至少不用使用runkit这样的扩展来重新定义类的代码库。

在PHP反射中没有一个函数允许你在不调用构造函数的情况下实例化一个新对象。

less hacky way

这是绝对不可能的,原因有二:

  1. 对象可序列化或不可序列化,
  2. serialize/unserialize是PHP围绕
  3. 对象持久化的最原生实现。

其他的一切都意味着更多的工作,更多的实现和更多的代码——所以很可能用你的话来说就是更hack。

Doctrine有一个包,你可以使用:https://github.com/doctrine/instantiator