php 如何合并两个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3314179/
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
How do I merge two objects?
提问by Rupert Madden-Abbott
Possible Duplicate:
What is the best method to merge two PHP objects?
可能的重复:
合并两个 PHP 对象的最佳方法是什么?
I have an object, $foo, which has some methods and properties already defined and another object, $bar, which is just a set of properties. I want to merge the entirety of $bar into $foo such that all the properties of $bar become properties of $foo.
我有一个对象 $foo,它已经定义了一些方法和属性,另一个对象 $bar,它只是一组属性。我想将整个 $bar 合并到 $foo 中,这样 $bar 的所有属性都成为 $foo 的属性。
So if beforehand I had, $bar->foobar, afterwards I should be able to use $foo->foobar.
所以如果之前我有 $bar->foobar,之后我应该可以使用 $foo->foobar。
At the moment, I am doing the following:
目前,我正在执行以下操作:
foreach($bar as $key => $value) {
$foo->$key = $value;
}
However, if I were using arrays, I would just do one of the following:
但是,如果我使用数组,我只会执行以下操作之一:
$foo += $bar;
$foo = array_merge($foo, $bar);
Is there a similar way of doing this with objects or am I doing it the right way already?
是否有类似的方法来处理对象,或者我是否已经以正确的方式这样做了?
Please note that I do not what $bar to itself become a property of $foo i.e. not $foo->bar->foobar
请注意,我不会让 $bar 本身成为 $foo 的属性,即不是 $foo->bar->foobar
采纳答案by J Cooper
If $bar has all of $foo's properties, then it is a Foo. Thus, your Bar class should extend (inherit from) Foo. (Or vice versa, if I got your names confused!)
如果 $bar 具有 $foo 的所有属性,那么它就是一个 Foo。因此,您的 Bar 类应该扩展(继承自)Foo。(反之亦然,如果我混淆了你的名字!)
If you don't want to use inheritance for some reason, you can keep one object inside the other, and redirect calls to the other's properties from the outer object dynamically via magic methods like __get() and __set (see here)
如果出于某种原因不想使用继承,您可以将一个对象保留在另一个对象中,并通过 __get() 和 __set 等魔术方法将调用从外部对象动态重定向到另一个对象的属性(请参见此处)
回答by zetanova
Try this code
试试这个代码
echo $obj->name; //show: carlos
echo $obj2->lastname; //show: montalvo here
$obj_merged = (object) array_merge((array) $obj, (array) $obj2);
$obj_merged->name; //show: carlos
$obj_merged->lastname; //show: montalvo here
回答by Sjoerd
There is no built-in function to copy all properties of one object to another one.
没有内置函数可以将一个对象的所有属性复制到另一个对象。
The way you do it is probably the simplest. An alternative to provide the class of $foo with a __get method which returns the property directly from $bar.
你这样做的方式可能是最简单的。为 $foo 类提供 __get 方法的替代方法,该方法直接从 $bar 返回属性。

