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

Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?(在 foreach 循环中声明的 PHP 变量是否在每次迭代时被销毁和重新创建?)
本文介绍了在 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 变量是否在每次迭代时被销毁和重新创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)