如何在php中使用“替代语法”而不是“花括号语法”? (使用Endswitch Syntactic Sugar)

时间:2014-02-19 18:05:13

标签: php syntax

这是我的PHP代码:
    

switch ($i) {
    case 0:
        echo '$i is 0.';
        break;
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        echo '$i is somewhere between 1 and 5.';
        break;
    case 6:
    case 7:
        echo '$i is either 6 or 7.';
    default:
        echo "I don't know how much \$i is.";
}
?>

现在,我如何使用替代语法而不是大括号语法来制作代码?

2 个答案:

答案 0 :(得分:2)

在这种情况下,我甚至不觉得有使用Switch的要求,最好使用if或if else语句。

if($i==0){
  echo "value is 0";
} else if($i>0 && $i<6){
  echo "value is between 1 and 5";
}else if($i>5 && $i<8){
  echo "value is 6 or 7";
}else{
  echo "unknown value";
}

答案 1 :(得分:2)

如果您想在此示例中使用替代语法,则问题的实际答案是:

switch ($i):
        case 0:
            echo '$i is 0.';
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            echo '$i is somewhere between 1 and 5.';
            break;
        case 6:
        case 7:
            echo '$i is either 6 or 7.';
        default:
            echo "I don't know how much \$i is.";
    endswitch;
    ?>