更改数组副本中的值会更改原始 arra 中的值



我对 php 中的变量有一些我不明白的问题。

这是该问题的简化代码示例。

//Create an initial array with an sub-array
$a = array();
$a['test'] = array(1,2);
//Create an reference to $a['test'] in $b
//Changing $b[0] should now change the value in $a['test'][0]
$b = &$a['test'];
$b[0] = 3;
//Create an copy of $a into $c
$c = $a;
//Change one value in $c, which is an copy of $a.
//This should NOT change the original value of $a as it is a copy.
$c['test'][1] = 5;
print_r($a);
print_r($b);
print_r($c);

这是输出:

Array
(
    [test] => Array
        (
            [0] => 3
            [1] => 5
        )
)
Array
(
    [0] => 3
    [1] => 5
)
Array
(
    [test] => Array
        (
            [0] => 3
            [1] => 5
        )
)

该脚本创建一个带有子数组的数组,并在其中放置两个值。

然后将对子数组的引用放入 b 中,并以这种方式更改 a 中的一个值。

然后我把一个复制到c中。

然后我更改 c 的一个值。

由于 c 是 a 的副本,我希望 c 上的更改不会影响 a。但输出讲述了一个不同的故事。

谁能解释为什么当变量只是$a的副本时,更改变量中的值$c影响$a中的值$c?为什么 $a 的值中有 5

您正在通过引用将$b分配给$a(这就是&前缀的作用)。对$b的任何更改都将有效地修改$a。只需强制声明分配:

$b = $a['test'];

$c 不会修改$a 。以下是正在发生的事情的顺序,以及为什么数组是相同的:

$a['test']被分配了一个1,2 .
的数组 $b被指定为对$a['test']的引用,并修改其值
然后$c被分配给$a,现在已被$b.
修改

我想我找到了自己问题的答案......在此页面上: http://www.php.net/manual/en/language.references.whatdo.php

我真的不明白它为什么要这样做。我确实明白我将来可能应该避免混合引用和数组。

我指的是本节:

但请注意,数组中的引用可能是 危险。使用 右侧的引用不会将左侧变成 引用,但数组中的引用保留在这些普通中 作业。这也适用于数组所在的函数调用 按值传递。例:

<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b
/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>

换句话说,数组的引用行为是在 逐个要素的基础;个人的参考行为 元素与数组的引用状态分离 容器。

您正在使用$b = &$a['test'];将引用$a传递给$b 因此

改变

$b = &$a['test'];

$b = $a['test'];