使开关使用===比较而不==比较在PHP中 [英] make switch use === comparison not == comparison In PHP
本文介绍了使开关使用===比较而不==比较在PHP中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法做到这一点,以便下面的代码仍然使用开关并返回b
而不是a
?谢谢!
Is there anyway to make it so that the following code still uses a switch and returns b
not a
? Thanks!
$var = 0;
switch($var) {
case NULL : return 'a'; break;
default : return 'b'; break;
}
当然,使用if语句是这样的:
Using if statements, of course, you'd do it like this:
$var = 0;
if($var === NULL) return 'a';
else return 'b';
但是对于更复杂的示例,这变得很冗长.
But for more complex examples, this becomes verbose.
推荐答案
Sorry, you cannot use a ===
comparison in a switch statement, since according to the switch() documentation:
请注意,开关/大小写比较松散.
Note that switch/case does loose comparison.
这意味着您必须提出解决方法.来自 松散比较表 ,则可以通过类型转换来利用NULL == "0"
为假的事实:
This means you'll have to come up with a workaround. From the loose comparisons table, you could make use of the fact that NULL == "0"
is false by type casting:
<?php
$var = 0;
switch((string)$var)
{
case "" : echo 'a'; break; // This tests for NULL or empty string
default : echo 'b'; break; // Everything else, including zero
}
// Output: 'b'
?>
这篇关于使开关使用===比较而不==比较在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文