PHP开关盒默认 [英] PHP switch case default

查看:88
本文介绍了PHP开关盒默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果前面有匹配的大小写,是否会评估switch语句的默认值?

例如:

switch ($x) {
  case ($x > 5): print "foo";
  case ($x%2 == 0): print "bar";
  default: print "nope";
}

所以对于x = 50,您会看到foobar,或者foobarnope?

解决方案

是的,如果不存在"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆