如果我在 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 变量是否在每次迭代时被销毁和重新创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
MySQLi准备好的语句&foreach 循环MySQLi prepared statement amp; foreach loop(MySQLi准备好的语句amp;foreach 循环)
mysqli_insert_id() 是从整个服务器还是从同一用户获Is mysqli_insert_id() gets record from whole server or from same user?(mysqli_insert_id() 是从整个服务器还是从同一用户获取记录?)
PHP MySQLi 无法识别登录信息PHP MySQLi doesn#39;t recognize login info(PHP MySQLi 无法识别登录信息)
mysqli_select_db() 需要 2 个参数mysqli_select_db() expects exactly 2 parameters(mysqli_select_db() 需要 2 个参数)
Php mysql pdo 查询:用查询结果填充变量Php mysql pdo query: fill up variable with query result(Php mysql pdo 查询:用查询结果填充变量)
MySQLI 28000/1045 用户“root"@“localhost"的访问MySQLI 28000/1045 Access denied for user #39;root#39;@#39;localhost#39;(MySQLI 28000/1045 用户“root@“localhost的访问被拒绝)