1

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.

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.