在 PHP 中使用 === 比较而不是 == 比较

2022-01-12 00:00:00 type-conversion 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'
?>

现场演示

相关文章