Add properties to stdClass object from another object

Florin picture Florin · Apr 16, 2010 · Viewed 52k times · Source

I would like to be able to do the following:

$obj = new stdClass;
$obj->status = "success";

$obj2 = new stdClass;
$obj2->message = "OK";

How can I extend $obj so that it contains the properties of $obj2, eg:

$obj->status //"success"

$obj->message // "OK"

I know I could use an array, add all properties to the array and then cast that back to object, but is there a more elegant way, something like this:

extend($obj, $obj2); //adds all properties from $obj2 to $obj

Thanks!

Answer

Chris Gutierrez picture Chris Gutierrez · Apr 16, 2010

This is more along the lines of they way that you didn't want to do it....

$extended = (object) array_merge((array)$obj, (array)$obj2);

However I think that would be a little better than having to iterate over the properties.