4

I have 2 objects.

Here is the output of the objects when I print them out with print_r method of the PHP.

Oject #1;

stdClass Object ( [id] => 1 [portal_id] => 1 [name=> NEVZAT )

Object #2;

stdClass Object ( [surname] => YILMAZ)

I want to concatenate these 2 objects to each other so at the end of the process I need an Object which contains all of the variables of the 2 objects;

stdClass Object ( [id] => 1 [portal_id] => 1 [name=> NEVZAT [surname] => YILMAZ )
WhoSayIn
  • 4,061
  • 2
  • 18
  • 19

2 Answers2

11

A simple way would be to temporarily cast the objects to arrays, merge those arrays, then case the resulting array back to a stdClass object.

$merged = (object) array_merge((array) $object_a, (array) $object_b);
salathe
  • 50,055
  • 11
  • 103
  • 130
  • looks OK, thank you, but I want to know if this is the only way. Because it may cause some performance issues, there are lots of type castings. – WhoSayIn Jun 05 '12 at 10:18
  • 1
    Of course it is not the **only** way. Re. performance issues, my only advice would be to worry about performance when performance becomes an issue. – salathe Jun 05 '12 at 11:06
6

Just copy over the attributes like so:

// assume $o1 and $o2 are your objects
// we copy $o1 attributes to $o2
foreach ($o1 as $attr => $value) {
        $o2->{$attr} = $value;
}
Ja͢ck
  • 166,373
  • 34
  • 252
  • 304