Add properties to stdClass object from another object

前端 未结 4 1805
悲哀的现实
悲哀的现实 2021-02-07 04:26

I would like to be able to do the following:

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

$obj2 = new stdClass;
$obj2->message = \"OK\";
相关标签:
4条回答
  • 2021-02-07 04:41

    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.

    0 讨论(0)
  • 2021-02-07 04:44

    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.

    0 讨论(0)
  • 2021-02-07 04:48

    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.

    0 讨论(0)
  • 2021-02-07 04:49

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

    0 讨论(0)
提交回复
热议问题