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

Ben*_*min 19 php oop reflection instantiation

要恢复已持久化的对象的状态,我想在不调用其构造函数的情况下创建该类的空实例,以便稍后使用Reflection设置属性.

我找到的唯一方法,就是Doctrine的做法,就是创建一个虚假的对象序列化,并对unserialize()它:

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

还有另一种不那么黑客的方法吗?

我期待在反思中找到这样的方式,但我没有.

cat*_*che 7

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

class Parent {
  protected $property;
  public function __construct($arg) {
   $this->property = $arg;
  }
}

class Child extends Parent {

  public function __construct() {
    //no parent::__construct($arg) call here
  }
}
Run Code Online (Sandbox Code Playgroud)

然后使用Child类型:

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