PHP array copy semantics: what it does when members are references, and where is it documented?
This code
<?php
$a = 10;
$arr1 = array(&$a);
$arr1[0] = 20;
echo $a; echo "\n";
$arr2 = $arr1;
$arr2[0] = 30;
echo $a;
produces
20
30
Obviously reference array members are "preserved", which can lead, for example, to some interesting/strange behavior, like
<?php
function f($arr) {
$arr[0] = 20;
}
$val = 10;
$a = array(&$val);
f($a);
echo $a[0];
?>
outputting
20
My question is: what is it for, where is it documen开发者_如何学Cted (except for a user comment at http://www.php.net/manual/en/language.types.array.php#50036) and the Zend Engine source code itself?
PHP's assignment by reference behavior is documented on the manual page "PHP: What References Do". You'll find a paragraph on array value references there, too, starting with:
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.
The page also explains your why your first code behaves like it does:
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.
精彩评论