PHP:具有未定义常量的switch语句

Just a quick question regarding how PHP handles switch statements.

If I had the following code

switch (APPLICATION_ENVIRONMENT) {
    case 'production':
        echo 'production';
        break;
    case 'stage':
        echo 'stage';
        break;
    default: //dev
        echo 'dev';
}

would this still evaluate to default if APPLICATION_ENVIRONMENT was not defined anywhere? Or would it throw out an error? Looking at existing source in the application im running, whoever has done this previously has done an if(defined()) on the constant first to check if it exists, which is a waste if switch can eval that properly for me

Thanks DJ

If undefined, APPLICATION_ENVIRONMENT would be interpreted by PHP as the string "APPLICATION_ENVIRONMENT", and so would fall through to the default since the string "APPLICATION_ENVIRONMENT" is not one of your defined switch cases.

echo APPLICATION_ENVIRONMENT;

PHP Notice: Use of undefined constant APPLICATION - assumed 'APPLICATION_ENVIRONMENT' in php shell code on line 1

PHP will issue a notice when it encounters an undefined constant, and, for better or worse, will process it under the assumption that you intended to quote it as a string.

It would evaluate the switch, however it would throw an error.

Try this instead:

$env = defined('APPLICATION_ENVIRONMENT') ? APPLICATION_ENVIRONMENT : null;

switch($env) {
  ..
}

If APPLICATION_ENVIRONMENT is undefined in the code, it will simply act as a string and print default switch value.

Switch statement need a variable. So even you defined APPLICATION_ENVIRONMENT somewhere in the code use it as switch($APPLICATION_ENVIRONMENT){..cases} instead of switch(APPLICATION_ENVIRONMENT){..cases}