开发者

How do I merge two objects? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the best method to merge two PHP objects?

I have an object, $foo, which has s开发者_运维技巧ome 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.

So if beforehand I had, $bar->foobar, afterwards I should be able to use $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


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


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!)

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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜