Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Switch statement with undefined constant

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

like image 634
Daniel K. Jones Avatar asked Apr 15 '26 04:04

Daniel K. Jones


1 Answers

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

Try this instead:

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

switch($env) {
  ..
}
like image 92
Ben Rowe Avatar answered Apr 16 '26 20:04

Ben Rowe