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
的引用吗?
推荐答案
有关问题的第二部分,请参阅 手册的数组页面,其中说明(quoting) :
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屋!