【问题标题】:PHP: issue with switch statement (wrong return)PHP:switch语句的问题(错误的返回)
【发布时间】:2019-01-24 10:18:41
【问题描述】:

我有这个方法:

private function convertStatusStringToIntZeroOrOne(string $status)
{

    $status = strtolower($status);

    switch ($status) {

        case "off":
        case "0":
        case 0:
            $int_status = 0;
            break;

        case "on":
        case "1":
        case 1:
            $int_status = 1;
            break;

        default:
            $int_status = 1;
            break;


    }

    return $int_status;
}

$status参数,当字符串“On”(O字母大写)时,返回0(零)。

当然,我需要 return 为 1。

谢谢

【问题讨论】:

  • 因为在测试0 时,您正在从字符串转换为整数。 'on' == 0 是真的。

标签: php switch-statement


【解决方案1】:

由于您在 switch 的选项中有数字 0 和 1,因此它使用了数字比较 - 数字的“开”是 0,因此它与 0 匹配。

由于您的参数类型为string,因此数字将被转换为字符串,因此请删除数字比较...

function convertStatusStringToIntZeroOrOne(string $status)
{
    $status = strtolower($status);

    switch ($status) {
        case "off":
        case "0":
            $int_status = 0;
            break;
        case "on":
        case "1":
            $int_status = 1;
            break;
        default:
            $int_status = 1;
            break;
    }

    return $int_status;
}
echo convertStatusStringToIntZeroOrOne("On");

虽然你可以将函数简化为...

function convertStatusStringToIntZeroOrOne(string $status)
{
    $status = strtolower($status);
    return ($status == "off" || $status == 0)?0:1;
}

【讨论】:

  • 可以进一步减少到return (int) ! in_array(strtolower($status), ['off', '0'], true); - 但不太清楚:-)
猜你喜欢
  • 2013-12-25
  • 2023-02-04
  • 2015-04-13
  • 2013-10-06
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2013-06-18
相关资源
最近更新 更多