【问题标题】:switch condtion going on first case on int 0在 int 0 上的第一种情况下切换条件
【发布时间】:2018-10-12 21:10:48
【问题描述】:

我有这样的代码:

function someFunction($myKey){
  switch($myKey){
     case 'equals':
       $condition = '=';
       break;
     case 'notequals':
       $condition = '!=';
       break;
     default:
        $condition = 'like';
        break;
  }
  return $condition;
}
echo someFunction(1);        // output 'like' good 
echo someFunction('equals'); // output '=' also good 
echo someFunction(0);        // but here output '=' why ?
echo someFunction(true);     // and here also '=' why ?

正如我所评论的,为什么 0true 使用第一种情况而不是默认情况?

虽然我修复了在切换条件之前将$myKey 转换为字符串 但我很好奇我在这里做错了什么。

【问题讨论】:

    标签: php variables switch-statement conditional-statements


    【解决方案1】:

    PHP switch 页面您可以看到它使用了Loose Comparison

    • 与整数0 比较,将字符串equals 转换为整数0
    • 与布尔值true 比较,将字符串equals 转换为布尔值true

    由于您正在比较字符串,请将参数转换为带有(string)strval() 的字符串:

    function someFunction($myKey){
        switch((string)$myKey){
         case 'equals':
           $condition = '=';
           break;
         case 'notequals':
           $condition = '!=';
           break;
         default:
            $condition = 'like';
            break;
      }
      return $condition;
    }
    

    【讨论】:

    • 哇,谢谢你的解释。
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2021-08-11
    • 2014-11-23
    • 1970-01-01
    • 2022-12-18
    • 2021-06-09
    • 2019-12-12
    • 2016-07-09
    相关资源
    最近更新 更多