问题描述
在 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 语句变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!