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

发布于 2024-08-29 03:25:12 字数 368 浏览 8 评论 0原文

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

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阳光下慵懒的猫 2024-09-05 03:25:13

您可以在 stdClass 对象之一上使用 get_object_vars() ,迭代这些对象,并将它们添加到另一个:

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

请注意,不确定您是否认为这更优雅。

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

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

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 storing them in the same place, take a look at this answer to a very similar question.

最后的乘客 2024-09-05 03:25:12

这更符合您不想这样做的方式......

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

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

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.

若水微香 2024-09-05 03:25:12

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

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

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

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

以及您想要的任意数量。

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

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

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

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

.... and as many as you wish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文