gpt4 book ai didi

PHP 数组复制语义 : what it does when members are references, 以及它在哪里记录?

转载 作者:行者123 更新时间:2023-12-04 06:25:36 26 4
gpt4 key购买 nike

这段代码

<?php

$a = 10;
$arr1 = array(&$a);

$arr1[0] = 20;
echo $a; echo "\n";

$arr2 = $arr1;
$arr2[0] = 30;

echo $a;

产生
20
30

显然,引用数组成员是“保留的”,例如,这可能导致一些有趣/奇怪的行为,例如
<?php

function f($arr) {
$arr[0] = 20;
}

$val = 10;
$a = array(&$val);

f($a);

echo $a[0];

?>

输出
20

我的问题是:它是干什么用的,它在哪里记录(除了 http://www.php.net/manual/en/language.types.array.php#50036 上的用户评论)和 Zend 引擎源代码本身?

最佳答案

PHP 的引用行为赋值记录在 manual page "PHP: What References Do" 上。 .你也会在那里找到一个关于数组值引用的段落,开头是:

While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add.



该页面还解释了您的第一个代码的行为原因:

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.

关于PHP 数组复制语义 : what it does when members are references, 以及它在哪里记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6072444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com