Search code examples
phpconstants

Check if a class constant exists


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")?


Solution

  • 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