Noahj Champion Noahj Champion - 3 years ago 177
PHP Question

How to check if a variable is a Magic Constant?

I don't find any way online or scratching through the PHP docs to do this.

Is there a friendly or light way check if a variable is a Magic Constant like

? Similar to

I want to check against the
passed and run some if/else conditions on it.

Small example.

function test($var) {

if ($var == 'string_value') {

// Do this...


elseif (is_magic_constant($var)) {

// Do this...


else {

// Do this...




Answer Source

If you call test(__FILE__);, __FILE__ is immediately expanded so that your test() function receives a string of the full file path.

If you call test('__FILE__'); it still receives a string, but then that string will be "__FILE__" and you can run that through defined($var); to see if it's a known constant.

There is no way to check if it's a magic constant. So you cannot distinguish them from the reserved constants, any of the constants defined by installed PHP extensions or from constants you define() yourself in your application. All you can check is whether the string in $var matches the name of a defined constant.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download