PHP Constant Does Not Exist: Notification

I would like to use constants as configuration variables in my PHP applications only when the constant does not exist (for some reason) it throws me a notification, but I would like it to be an error (or exception), just like when I try to repeat a non existing variable.

This is possible without using a separate function to get constant values, something like this:

echo $non_existing_variable; // Error
echo NON_EXISTING_CONSTANT; // Now also an error

I searched a little, but could not find anything.

It seems logical to me when I try to use a variable that does not exist, the execution of the code immediately terminates and throws an error, why is this not the case with constants?

+3
source share
6

defined , -

if (defined('CONSTANT')) {
    echo CONSTANT;
} else {
    throw new Exception('Undefined Constant.');
}

Edit:

, , , set_error_handler, .

+11

,

  • ,
  • , < Undefined class constant '
  • ,

, . , . PHP .

class Config{
    const CONFIG_ONE = 42;
}
//will produce a fatal error 
if(Config::CONFIG_TWO){
   //...
}

, . , hijinks (. set_error_handler).

, , , - singleton private class, . , , - undefined, .

+2
0

, , , , - php- , .

It seems kind of logical for me when I try to use a variable that does not exist. Code execution is executed immediately and throws an error, why is this not the case with constants?

Thanks, bye (-:

0
source

Source: https://habr.com/ru/post/1702528/


All Articles