实例化对象,而无需在PHP中调用其构造函数 [英] Instantiate an object without calling its constructor in PHP

查看:199
本文介绍了实例化对象,而无需在PHP中调用其构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要恢复已保留的对象的状态,我想创建一个空类的实例,而无需调用其构造函数,以稍后使用

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.

我发现的唯一方法(即 Doctrine 所做的方法)是创建伪造的序列化并unserialize()它:

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);
}

还有另一种更少的 hacky 方法来做到这一点吗?

Is there another, less hacky way, to do that?

我原本希望在Reflection中找到这样的方法,但是我没有.

I was expecting to find such a way in Reflection, but I did not.

推荐答案

更新: ReflectionClass :: newInstanceWithoutConstructor 可用!

这篇关于实例化对象,而无需在PHP中调用其构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆