从另一个对象向 stdClass 对象添加属性
我希望能够执行以下操作:
$obj = new stdClass;
$obj->status = "success";
$obj2 = new stdClass;
$obj2->message = "OK";
如何扩展 $obj 以便它包含 $obj2 的属性,例如:
$obj->status //"success"
$obj->message // "OK"
我知道我可以使用数组,将所有属性添加到数组中,然后将其转换回对象,但是有没有更优雅的方法,如下所示:
extend($obj, $obj2); //将$obj2中的所有属性添加到$obj
I would like to be able to do the following:
$obj = new stdClass;
$obj->status = "success";
$obj2 = new stdClass;
$obj2->message = "OK";
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); //adds all properties from $obj2 to $obj
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在
stdClass
对象之一上使用 get_object_vars() ,迭代这些对象,并将它们添加到另一个:请注意,不确定您是否认为这更优雅。
编辑:如果您不吝惜将它们实际存储在同一个地方,请查看这个答案非常相似的问题。
You could use get_object_vars() on one of the
stdClass
object, iterate through those, and add them to the other:Not sure if you'd deem that more elegant, mind you.
Edit: If you're not stingy about actually storing them in the same place, take a look at this answer to a very similar question.
看看对象克隆 http://php.net/manual/en/ language.oop5.cloning.php
have a look at object cloning http://php.net/manual/en/language.oop5.cloning.php
这更符合您不想这样做的方式......
但是我认为这比必须迭代属性要好一点。
This is more along the lines of they way that you didn't want to do it....
However I think that would be a little better than having to iterate over the properties.
如果该对象是 stdClass 的实例(在您的情况下),您可以简单地扩展您的对象,例如......
以及您想要的任意数量。
if the object is the instance of stdClass (that's in your case) you can simply extend your object like...
.... and as many as you wish.