简体   繁体   English

PHP 变量范围 - 在 foreach 循环中设置全局变量

[英]PHP variable scope - setting globals inside foreach loops

I am new-ish to PHP have read the PHP Variable scope docs and other Stackoverflow threads and can't get my head around why setting a global var inside a foreach loop doesn't work:我是 PHP 新手,已经阅读了PHP 变量范围文档其他 Stackoverflow 线程,但无法理解为什么在 foreach 循环中设置全局变量不起作用:

if (isset($regionsArr) && $page == 'regions') {
  $param = htmlspecialchars($_GET["region"]);
  foreach ($regionsArr as $item) {
    if ($item['region'] == $param) {
      global $curRegion;
      $curRegion = $item;
      echo $GLOBALS["curRegion"]["name"]; // works
    } else {
      $curRegion = null;
    }
  }
}
if (isset($GLOBALS["curRegion"])) {
  echo $GLOBALS["curRegion"]["name"]; // does not work
}

Thanks to @lawrencecherone for pointing out that I need to break;感谢@lawrencecherone 指出我需要break; out of the loop.跳出循环。

Without the brake, the loop continues and overrides $curRegion with null after it is successfully set in the loop.在没有刹车的情况下,循环继续并在循环中成功设置$curRegion用 null 覆盖它。

Note: if by stroke of luck your matched $item happened to be the very last item in the loop, then it wouldn't get overridden, but... yeah... just add break;注意:如果幸运的是你匹配的$item恰好是循环中的最后一个项目,那么它不会被覆盖,但是......是的......只需添加 break;

foreach ($regionsArr as $item) {
  if ($item['region'] == $param) {
    $curRegion = $item;
    break; // this kills the loop after $item['region'] matches $param
  } else {
    $curRegion = null;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM