默认为switch语句中的第一个选项? [英] default as first option in switch statement?

查看:156
本文介绍了默认为switch语句中的第一个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对此进行了测试,但效果很好,但对我来说看起来很奇怪.我是否应该担心这是非标准形式,它将在以后的PHP版本中删除,或者它可能会停止工作?我一直将默认情况作为最后一种情况,从未将其作为第一种情况...

I've tested this and it works fine, but it looks... weird... to me. Should I be concerned that this is nonstandard form which will be dropped in a future version of PHP, or that it may stop working? I've always had a default case as the final case, never as the first case...

switch($kind)
{
    default:
        // The kind wasn't valid, set it to the default
        $kind = 'kind1';
        // and fall through:

    case 'kind1':
        // Do some stuff for kind 1 here
        break;

    case 'kind2':
        // do some stuff for kind2 here
        break;

    // [...]

    case 'kindn':
        // do some stuff for kindn here
        break;

}

// some more stuff that uses $kind here...

(如果不清楚,我要确保$ kind有效,因此是默认值:case.但是开关也执行一些操作,然后在开关之后也使用$ kind.为什么默认:进入第一种情况,并设置$ kind)

(In case it's not obvious what I'm trying to do is ensure $kind is valid, hence the default: case. But the switch also performs some operations, and then $kind is used after the switch as well. That's why default: falls through to the first case, and also sets $kind)

建议?这是正常/有效的语法吗?

Suggestions? Is this normal/valid syntax?

推荐答案

这是一个不寻常的习惯用法,当您阅读它时会引起一点停顿,这是呵呵"的时刻.它可以工作,但是大多数人可能希望最后找到默认的情况:

It is an unusual idiom, it causes a little pause when you're reading it, a moment of "huh?". It works, but most people would probably expect to find the default case at the end:

switch($kind)
{
    case 'kind2':
        // do some stuff for kind2 here
        break;

    // [...]

    case 'kindn':
        // do some stuff for kindn here
        break;

    case 'kind1':
    default: 
        // Assume kind1
        $kind = 'kind1';

        break;

}

这篇关于默认为switch语句中的第一个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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