PHP中的数组在传递给函数时会复制为值还是对新变量的引用? [英] Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?
问题描述
1)当数组作为参数传递给方法或函数时,它是通过引用还是通过值传递?
1) When an array is passed as an argument to a method or function, is it passed by reference, or by value?
2)将数组分配给变量时,新变量是对原始数组的引用,还是新副本?
怎么办呢?
2) When assigning an array to a variable, is the new variable a reference to the original array, or is it new copy?
What about doing this:
$a = array(1,2,3);
$b = $a;
$b
是对$a
的引用吗?
推荐答案
For the second part of your question, see the array page of the manual, which states (quoting) :
数组分配总是涉及值 复制.使用引用运算符 通过引用复制数组.
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
给出的示例:
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
对于第一部分,最好的确定方法是尝试;-)
For the first part, the best way to be sure is to try ;-)
考虑以下示例代码:
function my_func($a) {
$a[] = 30;
}
$arr = array(10, 20);
my_func($arr);
var_dump($arr);
它将给出以下输出:
array
0 => int 10
1 => int 20
这表明该函数尚未修改作为参数传递的外部"数组:它作为副本而不是引用传递.
Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.
如果要通过引用传递它,则必须以这种方式修改函数:
If you want it passed by reference, you'll have to modify the function, this way :
function my_func(& $a) {
$a[] = 30;
}
输出将变为:
array
0 => int 10
1 => int 20
2 => int 30
因为,这一次,该数组已通过引用"传递.
As, this time, the array has been passed "by reference".
不要犹豫,阅读手册的参考资料部分:它应该回答您的一些问题;-)
Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)
这篇关于PHP中的数组在传递给函数时会复制为值还是对新变量的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!