Veynom Veynom - 1 year ago 140
PHP Question

What is the best method to merge two PHP objects?

We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply.

How do you copy a PHP object into a different object type

//We have this:

//We want the easiest way to get:


  • These are objects, not classes.

  • The objects contain quite a lot of fields so a foreach would be quite slow.

  • So far we consider transforming objects A and B into arrays then merging them using array_merge() before re-transforming into an object but we can't say we are proud if this.

Answer Source

If your objects only contain fields (no methods), this works:

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

This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download