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

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

Please see this code:

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

$userInfoArray         


        
4条回答
  •  广开言路
    2020-11-28 11:58

    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.

    Just look at this minimal example:

    
    

    Here, the output is:

    1
    2
    

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

提交回复
热议问题