在 foreach 循环中声明的 PHP 变量是否在每次迭代时被销毁和重新创建? [英] Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?

查看:41
本文介绍了在 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.

这篇关于在 foreach 循环中声明的 PHP 变量是否在每次迭代时被销毁和重新创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆