How does the “&” operator work in a PHP function?

后端 未结 4 2092
轮回少年
轮回少年 2020-11-28 11:42

Please see this code:

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

$userInfoArray         


        
4条回答
  •  庸人自扰
    2020-11-28 12:18

    When using the ampersand prior to a variable in a function call, it associates with the original variable itself. With that, the code you posted is saying that it will add 1 to the counter of the original array. Without the ampersand, it takes a copy of the data and adds to it, then returns the new counter of 11. The old array still remains intact at 10 and the new counter variable returned turns into 11.

    http://www.phpreferencebook.com/samples/php-pass-by-reference/

    is a good example.

提交回复
热议问题