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".
You use a CONSTANT when you know a value will never be changed. You use a variable when you want a value to be changed. You should use constants if you want to ensure that the value will not/cannot get changed anywhere after it's been defined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.
To check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true .
The basic difference between these two is that const defines constants at compile time, whereas define() defines them at run time. We can't use the const keyword to declare constant in conditional blocks, while with define() we can achieve that.
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
// )
// )
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With