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

3 Answers 3

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);
2
  • 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 5, 2012 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 5, 2012 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;
}
0
<?php
        class MergeObj {
            // Empty class
        }
         
        $objectA = new MergeObj();
        $objectA->a = 1;
        $objectA->b = 2;
        $objectA->d = 3;
         
        $objectB = new MergeObj();
        $objectB->d = 4;
        $objectB->e = 5;
        $objectB->f = 6;
         
        $obj_merged = (object) array_merge((array) $objectA,(array) $objectB);
                 
        print_r($obj_merged); 
?>

Output:

stdClass Object
(
    [a] => 1
    [b] => 2
    [d] => 4
    [e] => 5
    [f] => 6
)

Demo Link: https://onecompiler.com/php/3yn3amgjv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.