slinkhi
slinkhi

Reputation: 989

php is it possible to determine if a constant is user defined?

I know that in general I can check if a constant is defined with the following:

defined('MY_CONSTANT')
defined('PHP_EOL')

The first one is my own user-defined constant. The 2nd one is created by php. Both can be checked with defined() and return a boolean value.

My question is.. is there a way to determine whether it is a user-defined constant or a php-created constant? For example, the MY_CONSTANT should return some equivalent of "user defined" and PHP_EOL should return some equivalent of "php-defined".

Upvotes: 7

Views: 197

Answers (2)

Jason McCreary
Jason McCreary

Reputation: 72971

Use get_defined_constants() with a parameter of true to return a categorized array of all constants.

User-defined constants are under the user key:

print_r(get_defined_constants(true));
// outputs:
// Array (
//    [Core] => Array (
//      [PHP_EOL] => 1
//    )
//    [user] => Array (
//      [MY_CONSTANT] => 1
//    )
// )

Upvotes: 11

Ralph Ritoch
Ralph Ritoch

Reputation: 3440

See get_defined_constants

http://php.net/manual/en/function.get-defined-constants.php

$CheckConst = 'MY_CONSTANT';
$is_user_defined = isset(get_defined_constants (true)['user'][$CheckConst]);

Upvotes: 1

Related Questions