[英]PHP switch statement variable scope
In PHP, how is variable scope handled in switch statements? 在PHP中,如何在switch语句中处理变量作用域?
For instance, take this hypothetical example: 例如,采用这个假设的例子:
$someVariable = 0;
switch($something) {
case 1:
$someVariable = 1;
break;
case 2:
$someVariable = 2;
break;
}
echo $someVariable;
Would this print 0 or 1/2? 这会打印0还是1/2?
The variable will be the same in your whole portion of code : there is not variable scope "per block" in PHP. 变量在整个代码部分中都是相同的:PHP中没有“每个块”的变量范围。
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
,那么您输入一个switch
的case
,您的代码将输出1或2。
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 ; 另一方面,如果$something
不是1
也不是2
(例如,如果它被认为是0
,这是你发布的代码的情况,因为它没有被初始化为任何东西) ,你将不会输入任何一个case
块 and the code will output 0
. 并且代码将输出0
。
PHP does only have a global and function/method scope . PHP只有一个全局和函数/方法范围 。 So $someVariable
inside the switch
block refers to the same variable as outside. 因此, switch
块内的$someVariable
指的是与外部相同的变量。
But since $something
is not defined (at least not in the code you provided), accessing it raises a Undefined variable notice, none of the cases match (undefined variables equal null
), $someVariable
will stay unchanged and 0
will be printed out. 但由于没有定义$something
(至少在你提供的代码中没有定义),访问它会引发一个未定义的变量通知,没有一个匹配(未定义的变量等于null
), $someVariable
将保持不变, 0
将被打印出来。
它将打印1或2. PHP中的变量具有整个功能的范围。
如果在switch语句中更改$someVariable
的值,它将打印1或2,如果不改变,则打印0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.