WhoSayIn
WhoSayIn

Reputation: 4719

PHP - Concatenating 2 objects

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 )

Upvotes: 4

Views: 10909

Answers (3)

KAZI SAYED HOSSAIN
KAZI SAYED HOSSAIN

Reputation: 1

<?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

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173572

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;
}

Upvotes: 6

salathe
salathe

Reputation: 51950

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

Upvotes: 11

Related Questions