We have two PHP objects that we want to merge, but they are not subclasses of each other. We need an efficient method that avoids using slow loops.
If the objects only contain fields, we can use this method to merge them into a new object:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
This works by converting the objects to arrays, merging the arrays using the array_merge() function, and then converting the merged array back to an object.
$objectA->a; $objectA->b; $objectB->c; $objectB->d; // Merge the objects $objectC = (object) array_merge((array) $objectA, (array) $objectB); // Verify the merged object echo $objectC->a; // Output: Value of a from objectA echo $objectC->b; // Output: Value of b from objectA echo $objectC->c; // Output: Value of c from objectB echo $objectC->d; // Output: Value of d from objectB
This method also works if the objects have methods, although this has not been exhaustively tested.
The above is the detailed content of How to Efficiently Merge Two Unrelated PHP Objects?. For more information, please follow other related articles on the PHP Chinese website!