代码之家  ›  专栏  ›  技术社区  ›  Krystian Polska

PHP引用数组元素已更改,但未触摸[重复]

  •  2
  • Krystian Polska  · 技术社区  · 7 年前
    <?php
    
    $arr = array(1);
    $a =& $arr[0];
    $arr2 = $arr;
    $arr2[0]++;
    
    var_dump($arr);
    

    这部分代码输出 2 为什么?

    我们只触及了 arr2 不是通过引用指定的 $arr

    1 回复  |  直到 7 年前
        1
  •  2
  •   BeetleJuice    7 年前

    将一个阵列指定给下一个阵列时,将生成一个副本。但是因为 $arr[0] 是引用而不是值,是 所以最后, $arr2[0] 指的是同一件事。

    这更多的是关于引用而不是数组。未复制引用值。这也适用于对象。考虑:

    $ageRef = 7;
    
    $mike = new stdClass();
    $mike->age = &$ageRef; // create a reference
    $mike->fruit = 'apple';
    
    $john = clone $mike; // clone, so $mike and $john are distinct objects
    $john->age = 17; // the reference will survive the cloning! This will change $mike
    $john->fruit = 'orange'; // only $john is affected, since it's a distinct object
    
    echo $mike->age . " | " . $mike->fruit; // 17 | apple
    

    请参阅上的第一个用户说明 this documentation page this one .