If()vs switch() - 相同但有不同的行为?

时间:2010-12-02 20:11:23

标签: if-statement switch-statement

我想将if()条件转换为switch():

if($configuration['application'][$applicationName]['subdomain'] == true){
    foreach($configuration['language'] as $language){
        if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
            $_SESSION['language'] = $language['abbreviation'];
        }
    }

    // If no subdomain detected and redirection is enabled, set default language
    if(!isset($_SESSION['language'])){
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
    }
}
else {
    $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
}

对此:

switch($configuration['application'][$applicationName]['subdomain']){
    case true:
        foreach($configuration['language'] as $language){
            if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
                $_SESSION['language'] = $language['abbreviation'];
                break;
            }
        }
    default:
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
        break;
}

我认为它应该是相同的,但它的行为不同...... 交换机无法正常工作......

1 个答案:

答案 0 :(得分:1)

我已重新格式化您的代码,请检查以确保其仍然正确。

至于您的问题,首先,您在break;语句的末尾缺少case true:语句。 (break循环中的foreach只是突破了该循环,而不是case本身。