HelloPablo
HelloPablo

Reputation: 625

Cloning stdClass seems to clone as a reference

Came across this scenario, which I'm sure is me not understanding something OOP related, but doesn't quite make sense to me.

Why does the following PHP:

$prototype                      = new stdClass();
$prototype->someProperty        = new stdClass();
$prototype->someProperty->value = 0;

$clone1 = clone $prototype;
$clone2 = clone $prototype;

$clone1->someProperty->value = 200;
$clone2->someProperty->value = 100;

print_r($clone1);
print_r($clone2);

Output this:

stdClass Object
(
    [someProperty] => stdClass Object
        (
            [value] => 100
        )

)
stdClass Object
(
    [someProperty] => stdClass Object
        (
            [value] => 100
        )

)

And not this (as I expected):

stdClass Object
(
    [someProperty] => stdClass Object
        (
            [value] => 100
        )

)
stdClass Object
(
    [someProperty] => stdClass Object
        (
            [value] => 200
        )

)

I'll bet it's something to do with the nested stdClass() which is going over my head; if I remove the someProperty property it behaves as I'd expect), but as far as I can see I'm creating new objects and not assigning any references anywhere (either implicitly or as a result of just assigning the variable).

As a side question to this, is creating a nested object like this wrong?


Update

A bit more thinking and, would I be along the right lines thinking that my clones are indeed clones, but both contain a reference to the someProperty property of $prototype. So I'd need to do a deep clone?

Upvotes: 0

Views: 409

Answers (1)

lafor
lafor

Reputation: 12776

From TFM:

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

When you do: $prototype->someProperty = new stdClass(); an object of stdClass is created on stack, and a reference to it is assigned to someProperty. When $prototype is cloned, the clone's someProperty references the same object.

Upvotes: 2

Related Questions