Open In App

How to merge two PHP objects?

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Merging two PHP objects means combining their properties and values into a single object. This is typically done by copying the properties from one object to another, ensuring that both objects’ data are preserved in the resulting merged object without overwriting critical values.

Here we have some common approaches to merge two PHP objects:

Approach 1: Using array_merge() function

To merge two PHP objects using array_merge(), first, convert the objects into arrays using `(array)` type casting. Then, use array_merge() to combine their properties into one array, and finally, cast the merged array back to an object.
Example: In this example we merges two objects, objectA and objectB, by first casting them to arrays and using array_merge().

php
<?php
// PHP program to merge two objects

class Geeks {
    // Empty class
}

$objectA = new Geeks();
$objectA->a = 1;
$objectA->b = 2;
$objectA->d = 3;

$objectB = new Geeks();
$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
)

Approach 2: Using array_merge() Method

To merge two PHP objects using the array_merge() method, first cast the objects to arrays, then apply array_merge() to combine their properties. After merging, cast the resulting array back to an object, thus combining the objects into one.

Example: In this example we merges two objects and converts the merged array back into a specific class (Geeks) using the convertObjectClass() function, combining properties from both objects into a single instance.

php
<?php
// PHP program to merge two objects

class Geeks {
    // Empty class
}

$objectA = new Geeks();
$objectA->a = 1;
$objectA->b = 2;
$objectA->d = 3;

$objectB = new Geeks();
$objectB->d = 4;
$objectB->e = 5;
$objectB->f = 6;

// Function to convert class of given object
function convertObjectClass($array, $final_class) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($final_class),
        $final_class,
        strstr(serialize($array), ':')
    ));
}

$obj_merged = convertObjectClass(array_merge(
        (array) $objectA, (array) $objectB), 'Geeks');

print_r($obj_merged);

?>

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

Next Article

Similar Reads