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

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

Please see this code:

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

$userInfoArray         


        
4条回答
  •  遥遥无期
    2020-11-28 11:58

    Here the & character means that the variable is passed by reference, instead of by value. The difference between the two is that if you pass by reference, any changes made to the variable are made to the original also.

    function do_a_thing_v ($a) {
        $a = $a + 1;
    }
    $x = 5;
    do_a_thing_v($x);
    echo $x; // echoes 5
    
    function do_a_thing_r (&$a) {
        $a = $a + 1;
    }
    $x = 5;
    do_a_thing_v($x);
    echo $x; // echoes 6
    

提交回复
热议问题