douwudie8060 2014-02-04 23:57
浏览 37
已采纳

PHP会覆盖数组元素吗?

I have the following code that shows PHP overwrites Array elements of objects with the last iteration of the object. Why would it do such a thing? I want to keep a record of what happened to the object and I use an array to do this. Look at the results of the array as I change the object. Why does PHP do this. It seems to me like it could lead to serious errors. Even using unset() as recommended by others does not work. It would only work if I unset the ENTIRE object. But why would I want to do that if only 1 element has changed? If my object has 10 elements in it, and 1 changes, I need to copy the ENTIRE object into an array. The reasoning is irrelevant as to why I need to do that. I am more interested in finding out why PHP has this behavior. Is this a known bug?

<?php
$server->server = 'c17d7ae1-c298-4a1d-b7ee-2a3c9a2ab14d';
$servers['test1'] = $server;

print_r($servers);
unset($server->server);  // <----- WHY DOES THIS NOT WORK?

$server->server = 'f88043af-dcf6-4802-a3d7-91cb594da4b0';
$servers['test2'] = $server;
print_r($servers);
?>

RESULTS:

php test.php

Array
(
    [test1] => stdClass Object
        (
            [server] => c17d7ae1-c298-4a1d-b7ee-2a3c9a2ab14d
        )

)
Array
(
    [test1] => stdClass Object
        (
            [server] => f88043af-dcf6-4802-a3d7-91cb594da4b0  <--- This right here is WRONG
        )

    [test2] => stdClass Object
        (
            [server] => f88043af-dcf6-4802-a3d7-91cb594da4b0
        )

)
  • 写回答

3条回答 默认 最新

  • duan117890 2014-02-05 00:06
    关注

    When assiging objects to another variable, PHP doesn't copy the object, it creates an reference. That means, two variables are now pointing at the same object.

    In your code, you first set the property server. Afterwards, you create a reference to the object that $serverpoints to in $servers[0]. You then unset the property server- which does work fine. afterwards, you're setting it again - to a new value. Next you create another reference in $servers[1]. Now you got 3 variables all pointing to THE SAME OBJECT: $server, $servers[0] and $servers[0].

    If you really want to do it that way (stdClasses shouldn't be used as dynamic objects, this is the javascript way of doing it and while valid in PHP it contradicts OOP paradigmn), use cloneto copy the objects:

    $server->server = 'c17d7ae1-c298-4a1d-b7ee-2a3c9a2ab14d';
    $servers['test1'] = clone $server;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题