如何在For循环(作用域)中使用外部变量



简单的问题,我还没有看到答案:

如何在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声明但未使用"。警告。

答案很简单,这是由于JavaScript和PHP在我的VSCode IDE和智能之间的差异。

IDE: VScode

智能:PHP智能VSCode扩展

在PHP中:变量必须至少为read,以消除警告&;$idx声明但未使用。&;

在JS中:变量必须至少是writtenread,以消除警告&;$idx声明但未使用。&;

最新更新