将stdClass对象转换/广播到另一个类 [英] Convert/cast an stdClass object to another class

查看:77
本文介绍了将stdClass对象转换/广播到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方存储系统,无论出于什么原因,无论输入什么内容,它都只会返回stdClass对象.因此,我很想知道是否有一种方法可以将stdClass对象转换/转换为给定类型的完整对象.

I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

例如,类似以下内容的东西:

For instance something along the lines of:

//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;

我只是将stdClass转换为数组并将其提供给BusinessClass构造函数,但是也许有一种方法可以还原我不知道的初始类.

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

注意:我对更改存储系统"类型的答案不感兴趣,因为它不是关注点.请考虑将其更多地视为关于语言能力的学术问题.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.

欢呼

推荐答案

请参见允许的演员为:

  • (int),(integer)-强制转换为整数
  • (布尔),(布尔)-强制转换为布尔
  • (float),(double),(real)-强制转换为float
  • (字符串)-转换为字符串
  • (数组)-转换为数组
  • (对象)-投射到对象
  • (未设置)-强制转换为NULL(PHP 5)

您必须编写一个映射器,该映射器将从stdClass转换为另一个具体类.应该不难做.

You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.

或者,如果您情绪低落,则可以改写以下代码:

Or, if you are in a hackish mood, you could adapt the following code:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

将一个数组伪广播到某个类的对象.通过首先序列化数组,然后更改序列化的数据以使其表示某个类,可以实现这一目的.然后将结果反序列化为此类的实例.但是就像我说的那样,它有点黑,所以要期待副作用.

which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.

对于对象到对象,代码为

For object to object, the code would be

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(strstr(serialize($instance), '"'), ':')
    ));
}

这篇关于将stdClass对象转换/广播到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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