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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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”.

How to&Answers:

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
//    )
// )

Answer:

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]);