如何在 For 循环(范围)内使用外部变量

How to Use an Outside Variable Inside a For Loop (Scope)

我还没有在任何地方看到答案的简单问题:

如何在 for 循环内使用外部 $variable

在我的 PHP 代码中,我有一个 SplDoubleyLinkedList 满是朋友的名字,我正在一个接一个地遍历它们以用于比较当前的 if 语句$friend 名称参数的朋友。如何更改或定位 $idx 变量,以便在循环和 if 语句中看到它?

这不是与 SplDoubleyLinkedList 有关的问题,而只是 scoping

<?php

  function removeFriend($friendsList, $friend)
  {
    $idx = null; //how can I set this index variable from the inside of the for loop?
    for ($friendsList->rewind(); $friendsList->valid(); $friendsList->next()) {
      if($friendsList->current() === $friend){
        $idx = $friendsList->key(); //"$idx is declared but not used."
      }
    }
  }

?>

这是我的问题的一般示例:

<?php

function test()
  {
    $test = 0; //how can I set this index variable from the inside of the for loop?
    for ($i = 0; $i < 10; $i++) {
      $test = 1; //"$idx is declared but not used."
    }
  }
  
 ?>

如果这个确切的函数被放入一个 JS 文件,它不会显示这个“$idx is declared but not used”警告。

答案很简单,是由于 JavaScript 和 PHP 在我的 VSCode IDE 和 Intellisence 中的差异。

IDE: VScode

智能:PHP Intelephence VSCode 扩展

在PHP中:变量必须至少为read以消除警告“$idx is declared but not used.”

在 JS 中:变量必须至少为 writtenread 才能消除警告“$idx is declared but not used.”