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 语句变量范围
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Laravel 仓库 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
