<?php
$var = 0;
switch($var) {
case "a":
echo "I think var is a";
break;
case "b":
echo "I think var is b";
break;
case "c":
echo "I think var is c";
break;
default:
echo "I know var is $var";
break;
}
?>
也许其他人会发现这个迷人的和有答案。如果你运行它,当明确地它是I think the var is a
时,它会输出0
。现在,我非常肯定这与我们在switch
语句中使用字符串这一事实有关,但我们检查的变量是一个整数。有谁知道为什么PHP会这样做?这没什么大不了的,但今天确实给我带来了一些麻烦。
谢谢大家!
答案 0 :(得分:6)
如果您将integer
与string
进行比较,则string
会转换为number
。因此,您的代码段实际上相当于:
$var = 0;
switch($var) {
case 0: // "a" gets converted to 0.
echo "I think var is a";
break;
case 0: // "b" gets converted to 0.
echo "I think var is b";
break;
case 0: // "c" gets converted to 0.
echo "I think var is c";
break;
default:
echo "I know var is $var";
break;
}
当第一个案例主体被执行时,将产生I think var is a
作为输出。即使有3个候选人,也会选择第一个候选人,因为它出现在顶部。
答案 1 :(得分:1)