在 foreach 循环中声明的 PHP 变量是否在每次迭代时被销毁和重新创建?

2021-12-26 00:00:00 loops variables scope foreach php

如果我在 foreach 循环中声明一个变量,例如:

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

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

PHP 是否销毁它,并在每次迭代时重新创建它?换句话说,在性能方面这样做是否更明智:

Does PHP destroy it, and re-creates it at each iteration ? In other words, would it be smarter performance-wise to do:

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

预先感谢您的见解.

推荐答案

在你的第一个例子中:

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

$myVariable 在第一次迭代期间创建,然后在每次进一步迭代时覆盖.在离开你的脚本、函数、方法的范围之前,它不会随时被销毁......

$myVariable is created during the first iteration and than overwritten on each further iteration. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

在你的第二个例子中:

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

$myVariable 在任何迭代之前创建并设置为 null.在每次迭代期间 if 将被覆盖.在离开你的脚本、函数、方法的范围之前,它不会随时被销毁......

$myVariable is created before any iteration and set to null. During each iteration if will be overwritten. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

我没有提到主要区别.如果 $myArray 为空 (count($myArray) === 0) $myVariable 将不被创建在您的第一个示例中,但在您的第二个示例中,它的值为 null.

I missed to mention the main difference. If $myArray is empty (count($myArray) === 0) $myVariable will not be created in your first example, but in your second it will with a value of null.

相关文章