PHP switch statement variable scope(PHP switch 语句变量范围)
问题描述
在 PHP 中,switch 语句中的变量作用域是如何处理的?
In PHP, how is variable scope handled in switch statements?
例如,举个假设的例子:
For instance, take this hypothetical example:
$someVariable = 0;
switch($something) {
case 1:
$someVariable = 1;
break;
case 2:
$someVariable = 2;
break;
}
echo $someVariable;
这会打印 0 还是 1/2?
Would this print 0 or 1/2?
推荐答案
你的整个代码部分中的变量将是相同的:在 PHP 中没有每个块"的变量范围.
The variable will be the same in your whole portion of code : there is not variable scope "per block" in PHP.
所以,如果 $something 是 1 或 2,那么你输入的 case 之一switch,您的代码将输出 1 或 2.
So, if $something is 1 or 2, so you enter in one of the case of the switch, your code would output 1 or 2.
另一方面,如果 $something 不是 1 也不是 2 (例如,如果它被视为 0,您发布的代码就是这种情况,因为它没有初始化为任何东西),您将不会进入任何 case 块;并且代码将输出 0.
On the other hand, if $something is not 1 nor 2 (for instance, if it's considered as 0, which is the case with the code you posted, as it's not initialized to anything), you will not enter in any of the case block ; and the code will output 0.
这篇关于PHP switch 语句变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP switch 语句变量范围
基础教程推荐
- Web 服务器如何处理请求? 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的foreach复选框POST 2021-01-01
- php中的PDF导出 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
