up vote 1 down vote favorite
share [g+] share [fb]

Here is the code:

$obj = new stdClass;
$obj->AAA = "aaa";
$obj->BBB = "bbb";

$arr = array($obj, $obj);

print_r($arr);

$arr[1]->AAA = "bbb";
$arr[1]->BBB = "aaa";

print_r($arr);

And here is the output:

Array
(
    [0] => stdClass Object
        (
            [AAA] => aaa
            [BBB] => bbb
        )

    [1] => stdClass Object
        (
            [AAA] => aaa
            [BBB] => bbb
        )

)

Array
(
    [0] => stdClass Object
        (
            [AAA] => bbb
            [BBB] => aaa
        )

    [1] => stdClass Object
        (
            [AAA] => bbb
            [BBB] => aaa
        )

)

Can anybody explain to me why all object variables (that are in array) are changed?

And sorry for my bad english. I am not a native english speaker.

link|improve this question
feedback

2 Answers

up vote 3 down vote accepted

The array is storing two references to the same object, not two distinct objects, as represented below:

array(
    0 =>  ---|          stdClass
             |------->     [AAA] => bbb
    1 =>  ---|             [BBB] => aaa
)

If you want to copy an object, use clone, which performs a shallow copy of the object:

$arr = array($obj, clone $obj);
link|improve this answer
Thanks a lot! clone solved the problem. – kaac Jan 15 at 18:33
feedback

You need to create a new instance of the class

$obj2 = new stdClass;
$obj2->AAA = "bbb";
$obj2->BBB = "aaa";

$arr = array($obj, $obj2);

Otherwise your array contains 2 pointers to the same object. The update statement changes the underlying object.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.