从另一个对象向stdClass对象添加属性 [英] Add properties to stdClass object from another object

查看:193
本文介绍了从另一个对象向stdClass对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够执行以下操作:

I would like to be able to do the following:

$obj = new stdClass;
$obj->status = "success";

$obj2 = new stdClass;
$obj2->message = "OK";

如何扩展$ obj使其包含$ obj2的属性,例如:

How can I extend $obj so that it contains the properties of $obj2, eg:

$obj->status //"success"

$obj->message // "OK"

我知道我可以使用数组,将所有属性添加到数组中,然后将其强制转换回对象,但是还有一种更优雅的方法,如下所示:

I know I could use an array, add all properties to the array and then cast that back to object, but is there a more elegant way, something like this:

extend($ obj,$ obj2); //将所有属性从$ obj2添加到$ obj

extend($obj, $obj2); //adds all properties from $obj2 to $obj

谢谢!

推荐答案

这更像是您不想这样做的方式.

This is more along the lines of they way that you didn't want to do it....

$extended = (object) array_merge((array)$obj, (array)$obj2);

但是我认为这比必须遍历属性要好一些.

However I think that would be a little better than having to iterate over the properties.

这篇关于从另一个对象向stdClass对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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