Home >Backend Development >PHP Tutorial >How Can I Efficiently Merge PHP Objects Without Inheritance?
Efficient Merging of PHP Objects
When working with PHP5 objects that do not exhibit inheritance relationships, merging their contents can be a challenge. Traditional subclass-based solutions are inapplicable in this scenario.
Problem Statement
Consider the following objects:
$objectA->a; $objectA->b; $objectB->c; $objectB->d;
The goal is to obtain a third object, $objectC, that contains all the properties of $objectA and $objectB.
$objectC->a; $objectC->b; $objectC->c; $objectC->d;
Solution
The most efficient method for merging objects is to cast them to arrays using (array) and then merge them using array_merge(). The merged array can then be cast back to an object using (object):
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
This technique works effectively even if the objects have methods, as tested in both PHP 5.3 and 5.6.
Remarks
The above is the detailed content of How Can I Efficiently Merge PHP Objects Without Inheritance?. For more information, please follow other related articles on the PHP Chinese website!