将带有引用的数组分配给新数组允许写入引用,而无需访问分配给引用的原始变量


Assigning array carrying a reference to a new array permits writing to the reference without accessing the original variable assigned to the reference

$a = [1 => "A"];
$b = &$a[1];
$c = $a; 
$c[1] = "C";
echo $a[1];

输出:C(但我希望输出是A

显然,数组没有被=符号引用。

$c = $a; <-这应该复制$a并将其分配给$c,但是为什么在这里进行引用?

此外,如果我们简单地删除第二行 ( $b = &$a[1]; ),或将其替换为 ( $b = &$a; ),它的行为符合预期。

关于为什么会发生这种情况的任何解释?

您的代码段演示了有两种方法可以访问引用。

$b 变量提供了一种访问、修改和销毁引用的机制。

可以访问和修改$c中保存的引用的副本,但不能通过unset()销毁引用本身。

代码:(演示)

$a = [1 => "A"];
$b = &$a[1];
$c = $a; 
var_dump($c);    // array(1) { [1]=> &string(1) "A" }
unset($c[1]);    // does not affect the reference
var_dump($c);    // array(0) { }
var_dump($a);    // array(1) { [1]=> &string(1) "A" }
unset($b);       // now the reference is destroyed
var_dump($a);    // array(1) { [1]=> string(1) "A" }