問題描述
如果我在 foreach 循環(huán)中聲明一個變量,例如:
If I declare a variable inside a foreach loop, such as:
foreach($myArray as $myData) {
$myVariable = 'x';
}
PHP 是否銷毀它,并在每次迭代時重新創(chuàng)建它?換句話說,在性能方面這樣做是否更明智:
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';
}
預(yù)先感謝您的見解.
推薦答案
在你的第一個例子中:
foreach($myArray as $myData) {
$myVariable = 'x';
}
$myVariable
在第一次迭代期間創(chuàng)建,然后在每次進(jìn)一步迭代時覆蓋.在離開你的腳本、函數(shù)、方法的范圍之前,它不會隨時被銷毀......
$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
在任何迭代之前創(chuàng)建并設(shè)置為 null.在每次迭代期間 if 將被覆蓋.在離開你的腳本、函數(shù)、方法的范圍之前,它不會隨時被銷毀......
$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, ...
我沒有提到主要區(qū)別.如果 $myArray
為空 (count($myArray) === 0
) $myVariable
將不被創(chuàng)建在您的第一個示例中,但在您的第二個示例中,它的值為 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.
這篇關(guān)于在 foreach 循環(huán)中聲明的 PHP 變量是否在每次迭代時被銷毀和重新創(chuàng)建?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!