在案例中使用 isset 时,这个 php 开关发生了什么?
$a = true;
//b is unset;
switch(true) {
case ($a): echo 'a';
case (isset($b)): echo 'b';
default: echo 'c';
}
//outputs 'abc'. expected output is 'bc'
为什么输出不符合预期?
更新:预期输出“bc”是一个拼写错误,应读取为“ac”。
更新:我现在看到这段代码如何产生与预期不同的输出。第一个返回 true 的 case 之后的 switch 块中的每个代码段都将被执行,除非 switch 以中断结束。断点后不会测试其他情况。这就是我的错误所在,因为我期望测试在没有中断语句的情况下恢复每个案例。
$a = true;
//b is unset;
switch(true) {
case ($a): echo 'a';
case (isset($b)): echo 'b';
default: echo 'c';
}
//outputs 'abc'. expected output is 'bc'
Why is the output not as expected?
Update: Expected output 'bc' is a typo and should read 'ac'.
Update: I now see how this code produces different output than expected. EVERY code section in a switch block after the first case that returns true will be executed, unless the switch is ended by a break. After break point no other cases will be tested. This is where my mistake was as I expected testing to resume per case with the absence of break statements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Isius 编写的代码是正确的。这是找出以下哪种情况属实的好技巧。
您的代码无法正常工作,因为您没有为每种情况添加break语句。
它应该看起来像这样:
输出是“a”。我不知道你为什么期望得到“bc”输出。
Code written by Isius is correct. It's just the nice trick to find out, which of following cases is true.
Your code doesn't work properly because you didn't put break statement to each case.
It should look like that:
Output is 'a'. I don't know why you're expecting to get "bc" output.
当您明确将
$a
设置为true
时,我不知道为什么您期望输出为bc
。您正在比较true == true
这显然是一个积极的比较。switch
语句的作用是获取一个值,然后将其与case
语句指定的值进行松散的比较。两者的输入可以是表达式。一旦比较结果为正,就会执行代码,直到遇到break
或到达switch
语句的末尾。因此,要分解你的代码:
I have no idea why you expect the output to be
bc
, when you have clearly set$a
totrue
. You are comparingtrue == true
which will obviously be a positive comparison.What a
switch
statement does it take a value, then loosely compare it against the values specified bycase
statements. The input for both may be an expression. As soon as a comparison is positive, code is executed until abreak
is encountered or the end of theswitch
statement is reached.So, to break down your code:
这是很难读的,也没有任何意义。
这不是 switch 语句的工作原理。
This is pretty unreadable and it has no sense.
This is not how switch statements work.
我不确定你想在这里做什么,但我认为你对 switch 语句的工作原理有点困惑。 switch 语句本质上是一种拥有大量 IF 语句的更优雅的方式。因此,如果您有一个变量 $a 并且您想根据其值执行某种逻辑,那么您可以使用 IF 语句或条件语句来执行此操作。例如:
尽管您无法打开 true,但 true 没有打开的值 - 它只是 true。
I'm not sure what you are trying to do here bu I think you have got slightly mixed up about how a switch statement works. A switch statement is essentially a more elegant way of having lots of IF statements. So if you have a variable $a and you want to perform some sort of logic depending on its value then you could do it using either IF statements or conditionals. For example:
You can't switch on true though, true has no value to switch on - its just true.