How can I check if a constant is defined in a PHP class?
class Foo { const BAR = 1; }
Is there something like property_exists()
or method_exists()
for class constants? Or can I just use defined("Foo::BAR")
?
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 .
Note: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().
PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
The constant() function returns the value of a constant. Note: This function also works with class constants.
You can check if a constant is defined with the code below:
<?php if(defined('className::CONSTANT_NAME')){ //defined }else{ //not defined }
Yes, just use the class name in front of the constant name:
defined('SomeNamespace\SomeClass::CHECKED_CONSTANT');
http://www.php.net/manual/en/function.defined.php#106287
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