php 从另一个对象向 stdClass 对象添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2652659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:13:46  来源:igfitidea点击:

Add properties to stdClass object from another object

phpobjectpropertiesextendstdclass

提问by Florin

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 以使其包含 $obj2 的属性,例如:

$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

扩展($obj,$obj2);//将$obj2的所有属性添加到$obj

Thanks!

谢谢!

回答by Chris Gutierrez

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.

但是,我认为这比必须迭代属性要好一些。

回答by Mohit Mehta

if the object is the instance of stdClass (that's in your case) you can simply extend your object like...

如果对象是 stdClass 的实例(在您的情况下),您可以简单地扩展您的对象,例如...

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

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

$obj->message = $message;
$obj->subject = $subject;

.... and as many as you wish.

....和你想要的一样多。

回答by pinkgothic

You could use get_object_vars()on one of the stdClassobject, iterate through those, and add them to the other:

您可以在其中一个对象上使用get_object_vars()stdClass,遍历这些对象,然后将它们添加到另一个对象中:

function extend($obj, $obj2) {
    $vars = get_object_vars($obj2);
    foreach ($vars as $var => $value) {
        $obj->$var = $value;
    }
    return $obj;
}

Not sure if you'd deem that more elegant, mind you.

不知道你是否认为这样更优雅,介意你。

Edit: If you're not stingy about actually storingthem in the same place, take a look at this answer to a very similar question.

编辑:如果您对它们实际存储在同一个地方并不吝啬,请查看这个非常相似问题的答案