How to merge two objects?

Possible duplicate:
What is the best way to merge two PHP objects?

I have a $ foo object that has methods and properties already defined, and another object is $ bar, which is just a set of properties. I want to combine all $ bar into $ foo so that all $ bar properties become $ foo properties.

So, if earlier I had $ bar-> foobar, then later I could use $ foo-> foobar.

At the moment, I am doing the following:

foreach($bar as $key => $value) {
    $foo->$key = $value;
    }

However, if I were to use arrays, I would just do one of the following:

$foo += $bar;

$foo = array_merge($foo, $bar);

Is there a similar way to do this with objects, or am I already doing it right?

Note that I do not have $ bar becoming $ foo property for myself, and not $ foo-> bar-> foobar

+5
3

$bar $foo, Foo. , Bar () Foo. ( , !)

- , , __get() __set (. )

+3

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
+15

.

, , , . $foo __get, $bar.

0

All Articles