duande3134 2014-07-28 20:28
浏览 15
已采纳

克隆stdClass似乎克隆为参考

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?

  • 写回答

1条回答 默认 最新

  • du9843 2014-07-28 20:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号