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 中使用 === 比较而不是 == 比较
基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
