Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add properties to stdClass object from another object

Tags:

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!

like image 262
Florin Avatar asked Apr 16 '10 11:04

Florin


1 Answers

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.

like image 64
Chris Gutierrez Avatar answered Oct 07 '22 22:10

Chris Gutierrez