How to Merge 2 Objects in PHP

We need to merge 2 objects because we might need to use one of the object’s properties in the other object. In order to emrge 2 objects, we first convert them to arrays then use array_merge() function to merge them. Then cast the merged arraay to an object.

There is a limit with this method. This approach does not copy functions. So it requires both objects to not have methods and only contain variables.

$product1 = new stdClass();
$product1->id = 1;
$product1->name = 'LED Lamp';
$product1->brand = 'Xiao Mi';

$product2 = new stdClass();
$product2->id = 2;
$product2->name = 'Large Meeting Table';

$product = (object) array_merge((array) $product1, (array) $product2);

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close