PHP 的 For-each / for 行为 - Foreach 结束后值仍然可访问

PHP's For-each / for behaviour - Value remains accesible after Foreach ends

我有这段代码:

$exists = false;
foreach ($outsiderTests as $key => $outsiderTest) {
   $textExists = null;
   foreach ($tests as $test) {
       if ($outsiderTest->getName() == $test->getName()) {
           $exists = true;
           $existingTest = $test;
           break;
       } else
           $exists = false;
   }

   var_dump($existingTest, $test);
}

如您所见,我想看看 $tests 数组中是否存在与 outsiderTest 等效的项。我以为我必须将现有的等价物 $test 保存在另一个变量上,因为它会在 foreach 结束后消失,但事实并非如此。

$existingTest$test的值在我dump的时候是一样的。这很酷,让我能够摆脱提到的 $existingTest 变量,但让我想知道我是否理解 PHP 的循环功能。

$test 变量不是只存在于 foreach 范围内吗? PHP 是否临时保存执行 运行 通过的最后一个索引的值?

PHP的变量范围解释在这里:https://www.php.net/manual/en/language.variables.scope.php

实际上你有 2 个作用域:

  • 全局范围
  • 局部函数作用域

因此一个循环变量将可以在它的范围之外访问,并且将包含它拥有的最后一个值。这就是您出现这种行为的原因。

如果您有一个循环调用函数,那么您有多种选择:

  • 在函数内部用global关键字声明外部变量。
  • 使用 $GLOBALS 变量访问全局变量。
  • 使用 use () 语法将您需要的全局变量传递给 anonymous function