4

is there any way to simplify this code to avoid the need for an if to skip to the switch's default value?

I have a configuration table for different authentication methods for a http request, with an option not to set the value to default to a plain http request:

if(!isset($type)) {
    $type = "default";
}

switch ($type) {
   case "oauth":
       #instantinate an oauth class here
       break;
   case "http":
       #instantinate http auth class here
       break;
   default:
       #do an unprotected http request
       break;
}

I have no issue with the functionality, but I would like a cleaner solution to switch on an optional variable, is there any way to achieve that? Thanks!

4

4 回答 4

4

您不需要将变量设置为“默认值”。如果变量未设置或与所有其他定义的情况有任何不同的值,则将执行默认情况。但请记住:如果未设置变量并且您在开关中使用它,您将收到“注意:未定义变量”的通知。因此,如果您不想禁用通知,则必须检查变量是否已设置。

于 2013-09-23T23:58:55.023 回答
3

只是

switch ($type??'') {
    case "oauth":
        #instantinate an oauth class here
        break;
    case "http":
        #instantinate http auth class here
        break;
    default:
        #do an unprotected http request
        break;    
}

php >= 7 就足够了

于 2019-11-29T01:09:54.207 回答
1

如果您想在不通知的情况下简化它。尝试以下操作:

if(!isset($type)) {
    #do an unprotected http request
}else{
    switch ($type) {
       case "oauth":
           #instantinate an oauth class here
           break;
       case "http":
           #instantinate http auth class here
           break;
    }
}
于 2013-09-24T00:35:33.650 回答
-1

如果没有找到之前的案例,则该default案例是一个包罗万象的案例,因此您"default"无需检查变量是否为 isset 并将其分配给。

于 2013-09-23T23:50:46.890 回答