What is the best method to merge two PHP objects?

Technology CommunityCategory: PHPWhat is the best method to merge two PHP objects?
VietMX Staff asked 3 years ago
Problem
//We have this:
$objectA->a;
$objectA->b;
$objectB->c;
$objectB->d;

//We want the easiest way to get:
$objectC->a;
$objectC->b;
$objectC->c;
$objectC->d;

This works:

$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);

You may also use array_merge_recursive to have a deep copy behavior.

One more way to do that is:

foreach($objectA as $k => $v) $objectB->$k = $v;

This is faster than the first answer in PHP versions < 7 (estimated 50% faster). But in PHP >= 7 the first answer is something like 400% faster.