kaac
kaac

Reputation: 13

Object (into Array) variables in PHP

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.

Upvotes: 1

Views: 157

Answers (2)

user142162
user142162

Reputation:

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);

Upvotes: 3

Alex M
Alex M

Reputation: 3513

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.

Upvotes: 0

Related Questions