default as first option in switch statement?

2019-01-09 14:44发布

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...

(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?

9条回答
beautiful°
2楼-- · 2019-01-09 15:35

Kind of made me twinge at first, but that's just because we're not use to seeing things that way.

I would suggest that you document this highly, since some might call this "tricky" code. A noob or some future maintainer might come along and move it to the bottom where they're more comfortable with it and break the side-effect that is has being at the top.

查看更多
疯言疯语
3楼-- · 2019-01-09 15:38

This is how I'd probably do it... it's easy on the eye and keeps the functionality.

switch($kind)
{
    case 'kind1': default :
        // 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;
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-09 15:39

I'd personally prefer to do

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

    // [...]

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

    case 'kind1':
    default:
        $kind = 'kind1'; // Redundant if it's already set as 'kind1', but that doesn't make any difference to the code.
        // Do some stuff for kind 1 here
        break;

}
查看更多
登录 后发表回答