默认作为switch语句中的第一个选项?

2022-01-19 00:00:00 syntax switch-statement php

我已经对此进行了测试,它工作正常,但它看起来……很奇怪……对我来说.我是否应该担心这是非标准形式,将在 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;

}

相关文章