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:
$objectA->a;
$objectA->b;
$objectB->c;
$objectB->d;

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

Remarks:

  • 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.

12 Answers
12

Leave a Comment