PHP-reference / scope issue

 

 

    $arr = [1,2,3];
    foreach($arr as &$v) {
        //nothing todo.
    }
    foreach($arr as $v) {
        //nothing todo.
    }
    var_export($arr);
    //output:array(0=>1,1=>2,2=>2)

 

 

Due to pass by reference, and after the end of the foreach first, variable point $ v $ arr [2] address 

 

Since the block-level scope foreach does not exist, after the first end foreach variable $ v persists (cut point $ arr [2] memory address)

 

Thus, in the second foreach:

  The first cycle:

    $arr[2] = $v = $arr[0]; 

  Second cycle:

    $arr[2] = $v = $arr[1];

  Third cycle:

    ARR $ [2] = $ V = $ ARR [2]; // i.e. $ arr [2] = $ arr [2]; Since the second cycle $ ARR [2] is assigned $ arr [1] 2 i.e. Therefore $ arr [2] = 2

 

 

 

 

To avoid such problems affecting the program brings, it should pass a reference at the end of the cycle, use:

unset($v);

 

 

 

 

 

 

 

 

 

 

1

Guess you like

Origin www.cnblogs.com/Skate0rDie/p/11236216.html