0

I need to merge 2 custom objects of the same type. Here's what the class looks like:

<?php
class a{

    public $one;

    public $two;

          public function doSomething(){
              //do stuff
          }

}

I have got 2 instance of a that I need to merge together. I understand that I can use array_merge like this:

$result = (object)array_merge((array)$a1, (array)$a2);

But the problem is that I need the result to be of the a class and not stdObj.

If I do:

$result->doSomething()

an error results: PHP Fatal error: Call to undefined method stdClass::doSomething()

Since we cannot type cast to non-primitives, one cannot do: $result = (a)array_merge((array)$a1, (array)$a2);

Besides using a loop to iterate through one object and get and set values, are there more performant or neater ways to do this?

F21
  • 32,163
  • 26
  • 99
  • 170

1 Answers1

0

array_merge() is not what you want. As you rightly point out, they are not arrays

It sounds to me like you need what C++ calls a copy constructor.

Bascially, you are going to have to code it yourself, so add a function called merge() to your class which takes a single paramter which is an other obect of that class.

To code it you just need to assign each individual field of the parameter's data to your object's data.

read the PHP manual on object cloning for more info.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551