代码之家  ›  专栏  ›  技术社区  ›  St. John Johnson

重复数组但保留指针链接

  •  0
  • St. John Johnson  · 技术社区  · 16 年前

    // node(x, y)
    $array[0] = new node(15, 10);
    $array[1] = new node(30, -10);
    $array[2] = new node(-2, 49);
    
    // Some sort of copy system
    $array2 = $array;
    
    // Just to show modification to the array doesn't affect the source array
    array_pop($array2);
    if (count($array) == count($array2))
      echo "Fail";    
    
    // Changing the node value should affect the source array
    $array2[0]->x = 30;
    if ($array2[0]->x == $array[0]->x)
       echo "Goal";
    

    最好的办法是什么?

    2 回复  |  直到 16 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    如果使用PHP5:

    我得到:

    Goal
    

    当我运行它的时候。

    这很可能是因为 $array 已经是引用。

    this question . 尽管他希望达到相反的效果,但理解数组复制在PHP中的工作原理可能会有所帮助。

    这种行为,当用对象复制数组时,对对象的引用被复制而不是对象本身, was reported as a bug . 但目前还没有新的消息。


    你为什么还用它? )

    $array2 = array();
    
    for($i = 0; $i<count($array); $i++) {
        $array2[$i] = &$array[$i];
    }
    
        2
  •  0
  •   Giovanni Di Milia    16 年前

    有段时间我不写PHP代码,但会写代码

    // Some sort of copy system
    $array2 = $array;
    

    真的有用吗?