PHP switch case 默认 [英] PHP switch case default

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

问题描述

如果 switch 语句的默认值在它之前有匹配的大小写,它会被评估吗?

Will the default of a switch statement get evaluated if there's a matching case before it?

例如:

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

所以对于 x = 50,你会看到 foobar,或者 foobar不是?

so for x = 50, you'd see foo and bar, or foo and bar and nope?

推荐答案

是的,如果没有break",那么第一个匹配到的case之后的所有动作都会被执行.控制流将遍历"所有后续 case,并执行每个后续 case 下的所有操作,直到 break; 语句遇到,或者直到到达 switch 语句的末尾.

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.

在您的示例中,如果 $x 的值为 50,您实际上会看到 "nope".

In your example, if $x has a value of 50, you would actually see "nope".

请注意,switch 实际上是在 switch 关键字后面的表达式和 case 关键字后面的每个表达式之间执行简单的相等测试.

Note that switch is actually performing a simple equality test, between the expression following the switch keyword, and each expression following the case keyword.

您的示例很不寻常,因为它只会在 $x 的值为 0 时显示 "foo".(实际上,当 $x 的值为 0 时,您会看到是foo bar nope".)

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".)

评估 case 关键字后面的表达式,在您的情况下,示例返回 0(如果条件测试为假)或 1(如果条件测试为真).switch 将与 $x 比较的值(0 或 1).

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 switch case 默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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