PHP开关盒默认 [英] PHP switch case default
问题描述
如果前面有匹配的大小写,是否会评估switch语句的默认值?
例如:
switch ($x) {
case ($x > 5): print "foo";
case ($x%2 == 0): print "bar";
default: print "nope";
}
所以对于x = 50,您会看到foo
和bar
,或者foo
和bar
和nope
?
是的,如果不存在"break",则将在第一个匹配的case
之后执行所有操作.控制流将遍历"所有后续的case
,并在每个后续的case
下执行所有操作,直到遇到break;
语句,或者直到到达switch
语句的结尾. /p>
在您的示例中,如果$ x的值为50,则您实际上会看到"nope"
.
请注意,switch
实际上是在switch
关键字后面的表达式和case
关键字后面的每个表达式之间执行简单的相等性测试.
您的示例很不寻常,因为当$ x的值为0时,它只会显示"foo"
.(实际上,当$ x的值为0时,您会看到"foo bar nope". )
计算case
关键字后面的表达式,在您的情况下,示例返回0(如果条件测试为false)或1(如果条件测试为true).就是switch
与$x
相比较的那个值(0或1).
Will the default of a switch statement get evaluated if there's a matching case before it?
ex:
switch ($x) {
case ($x > 5): print "foo";
case ($x%2 == 0): print "bar";
default: print "nope";
}
so for x = 50, you'd see foo
and bar
, or foo
and bar
and nope
?
Yes, if there is no "break", then all actions following the first case
matched will be executed. The control flow will "falls through" all subsequent case
, and execute all of the actions under each subsequent case
, until a break;
statement is encountered, or until the end of the switch
statement is reached.
In your example, if $x has a value of 50, you would actually see "nope"
.
Note that switch
is actually performing a simple equality test, between the expression following the switch
keyword, and each expression following the case
keyword.
Your example is unusual, in that it will only display "foo"
when $x has a value of 0. (Actually, when $x has a value of 0, what you would see would be "foo bar nope".)
The expression following the case
keyword is evaluated, which in your case, example return a 0 (if the conditional test is false) or a 1 (if the conditional test is true). And it's that value (0 or 1) that switch
will compare to $x
.
这篇关于PHP开关盒默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!