Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?

前端 未结 4 1672
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 15:12

If I declare a variable inside a foreach loop, such as:

foreach($myArray as $myData) {
    $myVariable = \'x\';
}

Does PHP destroy it, and

4条回答
  •  情歌与酒
    2020-12-16 15:52

    The problem is $myVariable is not truly local to foreach only. So it can clobber a global variable under the same name.

    A way around that is make your foreach an inline anonymous function.

    E.g.

    $myforeach=function(&$myArray){ // pass by ref only if modifying it
      foreach($myArray as $myData) {
        $myVariable = 'x';
      }
    };
    $myforeach($myArray);  // execute anonymous.
    

    This way you guarantee it will not step on other globals.

提交回复
热议问题