Noahj Champion Noahj Champion - 3 years ago 161
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

__FILE__
or
__DIR__
? Similar to
is_callable()
?

I want to check against the
$var
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...

}

}

test('string_value');
test(__FILE__);

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