How to merge two PHP objects?
Given two objects of same class and the task is to merge both objects into single object.
Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass.
Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2. This may nullify the resulting elements in final object if array in argument2 has null values.
Note: Functions are not copied using this approach. Only use this approach if class only contain variables.
stdClass Object ( [a] => 1 [b] => 2 [d] => 4 [e] => 5 [f] => 6 )
Approach 2: Merge the object using array_merge() method and convert this merged array to object using convertObjectClass function. This function is used to convert object of the initial class into serialized data using serialize() method. Unserialize the serialized data into instance of the final class using unserialize() method. Using this approach obtain an object of user defined class Geeks rather the standard class stdClass.
Geeks Object ( [a] => 1 [b] => 2 [d] => 4 [e] => 5 [f] => 6 )
Approach 3: Create a new object of the original class and assign all the properties of both objects to this new object by using foreach loop. This is a simple and clean approach of merging two objects.
Geeks Object ( [a] => 1 [b] => 2 [d] => 3 [e] => 4 [f] => 5 [g] => 6 )