开关评价 [英] Switch evaluations
问题描述
我最近就 switch
如何处理比较产生了争论,需要帮助解决这个问题.
I recently got into an argument over how switch
handles comparisons, and need help settling it.
如果我写一个 switch
如:
switch ($x){
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
它等价于哪个 if
语句?A 还是 B?
Which if
statement is it equivalent to? A or B?
// A
if ($x > 5) {
echo "foo";
} elseif ($x < 5) {
echo "bar";
} else {
echo "five";
}
// B
if ($x == ($x > 5)) {
echo "foo";
} elseif ($x == ($x < 5)) {
echo "bar";
} else {
echo "five";
}
推荐答案
给大家澄清一下:
相当于B
.
它不是两者",有时不是一个,有时是另一个,它总是B
.要了解为什么有时会看到表明它可能是 A
的结果,您需要了解 类型强制在 PHP 中的工作原理.
It is not "both", it is not sometimes its one, sometimes it is the other, it is always B
. To understand why you sometimes see results that indicate that it might be A
, you need to understand how type coercion works in PHP.
如果您向 switch
的参数"传递一个 falsey 值,并且您在 case
中使用了 表达式 导致布尔值,它们只会在您的表达式计算结果为 FALSE
时匹配.
If you pass in a falsey value to the "argument" of switch
and you use expressions in your case
s that result in a boolean value, they will only match if your expression evaluates to FALSE
.
switch
基本上是一个巨大的 if
/elseif
树,它执行松散比较(==
而不是 ==
code>===) 传递给 switch
的值(表达式的左侧)和 case
中的表达式(右侧).
switch
is basically a huge if
/elseif
tree that performs loose comparisons (==
instead of ===
) between the value passed to switch
(the left side of the expression) and the expression in the case
s (the right side).
这个可以很好地证明对您的代码进行修改:
This can be proved quite nicely with a variation on your code:
$x = 0;
switch ($x) {
case $x > -1: // This is TRUE, but 0 == FALSE so this won't match
echo "case 1";
case $x == -1: // This is FALSE, and 0 == FALSE so this will match
echo "case 2";
}
如果我们将其转换为两个 if
/elseif
树:
And if we convert that to the two if
/elseif
trees:
A:
$x = 0;
if ($x > -1) {
// It matches here
echo "case 1";
} else if ($x == -1) {
// and not here
echo "case 2";
}
B:
$x = 0;
if ($x == ($x > -1)) {
// It doesn't match here
echo "case 1";
} else if ($x == ($x == -1)) {
// ..but here instead
echo "case 2";
}
这篇关于开关评价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!