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.
推荐答案
抱歉,您不能在 switch 语句中使用 ===
比较,因为根据 switch() 文档:
Sorry, you cannot use a ===
comparison in a switch statement, since according to the switch() documentation:
请注意,switch/case 的比较比较松散.
Note that switch/case does loose comparison.
这意味着您必须想出一个解决方法.来自松散比较表,您可以通过类型转换来利用 NULL == "0"
为 false 的事实:
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 中使用 === 比较而不是 == 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中使用 === 比较而不是 == 比较


- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01