在PHP数组按值或按引用传递? [英] are arrays in php passed by value or by reference?
问题描述
当一个数组作为参数传递给方法或函数传递是按引用传递?
When an array is passed as an argument to a method or function is it passed by reference?
关于这样内容:
What about doing this:
$a = array(1,2,3);
$b = $a
时的$ B $到一个参考?
Is $b a reference to $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 ;-)
考虑code的这个例子:
Consider this example of code :
function my_func($a) {
$a[] = 30;
}
$arr = array(10, 20);
my_func($arr);
var_dump($arr);
这会给这样的输出:
It'll give this output :
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".
结果
不要犹豫,阅读href=\"http://php.net/manual/en/language.references.php\">引用的解释手册的部分的
Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)
这篇关于在PHP数组按值或按引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!