PHP 引用数组元素在未触及的情况下更改
PHP Reference Array element changed without touching
<?php
$arr = array(1);
$a =& $arr[0];
$arr2 = $arr;
$arr2[0]++;
var_dump($arr);
这部分代码输出2
。
为什么?
我们只触及了 arr2
的第一个元素,它不是通过引用 $arr
赋值的。不对同一个数组进行别名,那是为什么?
当您将一个数组分配给下一个数组时,会生成一个副本。但是因为 $arr[0]
处的元素是引用而不是值,所以制作了 reference 的副本,所以最后 $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 and also this one 上的第一条用户注释。
<?php
$arr = array(1);
$a =& $arr[0];
$arr2 = $arr;
$arr2[0]++;
var_dump($arr);
这部分代码输出2
。
为什么?
我们只触及了 arr2
的第一个元素,它不是通过引用 $arr
赋值的。不对同一个数组进行别名,那是为什么?
当您将一个数组分配给下一个数组时,会生成一个副本。但是因为 $arr[0]
处的元素是引用而不是值,所以制作了 reference 的副本,所以最后 $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 and also this one 上的第一条用户注释。