“&"如何运算符在PHP函数中工作? [英] How does the "&" operator work in a PHP function?

查看:86
本文介绍了“&"如何运算符在PHP函数中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看此代码:

function addCounter(&$userInfoArray) {
    $userInfoArray['counter']++;
    return $userInfoArray['counter'];
}

$userInfoArray = array('id' => 'foo', 'name' => 'fooName', 'counter' => 10);
$nowCounter = addCounter($userInfoArray);

echo($userInfoArray['counter']);

这将显示11.

但是!如果您在功能参数中删除&"运算符,则结果将为10.

But! If you remove "&"operator in the function parameter, the result will be 10.

这是怎么回事?

推荐答案

&运算符告诉PHP在将数组传递给函数时不要复制该数组.而是将对数组的引用传递到函数中,因此该函数将修改原始数组,而不是副本.

The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.

只看这个最小的例子:

<?php
function foo($a) { $a++; }
function bar(&$a) { $a++; }

$x = 1;
foo($x);
echo "$x\n";    
bar($x);
echo "$x\n";
?>

在这里,输出为:

1
2

–对foo的调用未修改$x.另一方面,对bar的调用确实做到了.

– the call to foo didn’t modify $x. The call to bar, on the other hand, did.

这篇关于“&amp;"如何运算符在PHP函数中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆