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 )
- ES6 | Merge Objects
- Extract unique objects by attribute from array of objects.
- PHP | Objects
- R - Objects
- Perl | Objects in OOPs
- Scala | Package Objects
- Bootstrap 4 | Media Objects
- Media Objects in Bootstrap with Examples
- Understanding Classes and Objects in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.