在 PHP 中使用 === 比较而不是 == 比较 [英] make switch use === comparison not == comparison In PHP

查看:38
本文介绍了在 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 中使用 === 比较而不是 == 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆