PHP Pass by reference error after using same var

前端 未结 3 777
暖寄归人
暖寄归人 2021-01-15 01:40

Take a look to this code, and help me to understand the result

$x = array(\'hello\', \'beautiful\', \'world\');
$y = array(\'bye bye\',\'world\', \'harsh\');         


        
相关标签:
3条回答
  • 2021-01-15 02:26
    // ...
    $v = "DONT CHANGE!";
    unset($v);
    // ...
    

    because $v is still a reference, which later takes the last item in the last foreach loop.

    EDIT: See the reference where it reads (in a code block)

    unset($value); // break the reference with the last element

    0 讨论(0)
  • 2021-01-15 02:32

    Foreach loops are not functions.An ampersand(&) at foreach does not work to preserve the values like at functions. So even if you have $var in the second foreach () do not expect it to be like a "ghost" out of the loop.

    0 讨论(0)
  • 2021-01-15 02:38

    After this loop is executed:

    foreach ($x as $n => &$v) { }
    

    $v ends up as a reference to $x[2]. Whatever you assign to $v actually gets assigned $x[2]. So at each iteration of the second loop:

    foreach ($y as $n => $v) { }
    

    $v (or should I say $x[2]) becomes:

    • 'bye bye'
    • 'world'
    • 'harsh'
    0 讨论(0)
提交回复
热议问题