将整数0作为切换参数将采用第一个结果“ foo”:
$data=0; // $data is usually coming from somewhere else, set to 0 here to show the problem
switch ($data) :
case "anything":
echo "foo";
break;
case 0:
echo "zero";
break;
default:
echo "bar";
endswitch;
如何更改此设置,以便交换机将按预期写入“零”?
switch / case语句使用松散比较,无论0 == "anything"
是否喜欢,它都是true
:
[...]如果您将数字与字符串进行比较,或者比较涉及数字字符串,则每个字符串都将转换为数字,然后进行数字比较。这些规则也适用于switch语句。[...]
var_dump(0 == "a"); // 0 == 0 -> true
一种解决方案是将所有case语句更改为字符串,并进行字符串比较:
$data = 0;
switch ((string) $data): ## <- changed this
case "anything":
echo "foo";
break;
case "0": ## <- and this
echo "zero";
break;
default:
echo "bar";
endswitch;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句