20

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!

Florin
  • 2,891
  • 4
  • 19
  • 26

4 Answers4

33

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.

Chris Gutierrez
  • 4,750
  • 19
  • 18
  • After all, seems the most 'elegant', even though it involves a cast to array and back. By the way, how expensive is a object-to-array cast ? Does it involve a loop through all properties which are then added as keys to the array? – Florin Apr 19 '10 at 13:21
12

if the object is the instance of stdClass (that's in your case) you can simply extend your object like...

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

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

$obj->message = $message;
$obj->subject = $subject;

.... and as many as you wish.

Mohit Mehta
  • 1,283
  • 12
  • 21
5

You could use get_object_vars() on one of the stdClass object, iterate through those, and add them to the other:

function extend($obj, $obj2) {
    $vars = get_object_vars($obj2);
    foreach ($vars as $var => $value) {
        $obj->$var = $value;
    }
    return $obj;
}

Not sure if you'd deem that more elegant, mind you.

Edit: If you're not stingy about actually storing them in the same place, take a look at this answer to a very similar question.

Community
  • 1
  • 1
pinkgothic
  • 6,081
  • 3
  • 47
  • 72
  • 1
    A valid solution, but I guess the cast-to-array-and-back method does the same thing, except it's done internally in the php engine which should be a bit faster. – Florin Apr 19 '10 at 13:22
  • Absolutely. Hence not being sure whether this would class as 'more elegant'. Casts may be ugly, but they're not really ugly enough. :) – pinkgothic Apr 19 '10 at 13:57
1

have a look at object cloning http://php.net/manual/en/language.oop5.cloning.php

pinaki
  • 5,393
  • 2
  • 24
  • 32