php - PHP 中的数组引用混淆

标签 php

$arr = array(1);
$a = & $arr[0];

$arr2 = $arr;
$arr2[0]++;

echo $arr[0],$arr2[0];

// Output 2,2

你能帮我看看怎么可能吗?

最佳答案

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

/* 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! */

关于php - PHP 中的数组引用混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12297239/

相关文章:

php - 在 PHP 中使用 CSV 文件更新表的内容

php - 如何在 Slim 中向我的 Twig 模板添加自定义过滤器?

PHP删除数据库连接

php - 防止值在同一天重复

javascript - 使用 JSON.stringify 且无法访问 JSON 数组

javascript - 在php中执行一个php函数

php - 在 Symfony 3.1 中升级时,FOSUser 需要完全身份验证

javascript - 在将PHP变量传递到函数中的同时调用PHP中的Javascript函数

PHP:将匿名函数作为参数传递

php - CURL 和 HTTPS, "Cannot resolve host"