71

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

Martin Majer
  • 3,274
  • 4
  • 23
  • 36

5 Answers5

86

You can check if a constant is defined with the code below:

<?php
if(defined('className::CONSTANT_NAME')){
  //defined
}else{
  //not defined
}
Daan
  • 12,099
  • 6
  • 34
  • 51
  • 3
    and `constant('className::CONSTANT_NAME')` to retrieve it. – Ismail Oct 30 '17 at 14:04
  • 1
    ```className``` needs to be fully-qualified. Usually I do ```$class = get_class($obj); echo defined("$class::CONSTANT_NAME"));```. For more complex cases is better to use ```ReflectionClass```. – Kamafeather Jun 05 '18 at 09:51
  • 2
    Also, from *PHP >= 7.1.0* there you can also use ```new \ReflectionClassConstant($class, 'CONSTANT_NAME');``` and ```try``` to ```catch``` an eventual ```ReflectionException``` in case the constant doesn't exist on the class. More complex checking, but not less correct; ```if/else``` is just replaced by a ```try/catch``` depending on the developer preferences or style. – Kamafeather Jun 05 '18 at 10:03
  • 1
    Using late static binding you can use `if (defined(static::class . '::CONSTANT')) { $value = static::CONSTANT; } else { throw \RuntimeException('Class '.static::class.' needs constant CONTANT'); }`. – Radek Pech Oct 07 '22 at 11:54
68

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

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
Savageman
  • 9,257
  • 6
  • 40
  • 50
  • 10
    Remember also to add any namespace to the string, aka: defined('my\name\space\ClassName\property') – polesen May 07 '15 at 13:37
  • It is useful to know that you can use `constant('SomeNamespace\SomeClass::CHECKED_CONSTANT')` to get its value – Ormoz Aug 15 '21 at 03:54
20

You have 3 ways to do it:

defined()

[PHP >= 4 - most retro-compatible way]

$class_name = get_class($object); // remember to provide a fully-qualified class name
$constant = "$class_name::CONSTANT_NAME";
$constant_value = defined($constant) ? $constant : null;

Note: using defined() on a private constant (possible from PHP7.1) will throw error: "Cannot access private const". While using ReflectionClass or ReflectionClassConstant will work.

ReflectionClass

[PHP >= 5]

$class_reflex = new \ReflectionClass($object);
$class_constants = $class_reflex->getConstants();
if (array_key_exists('CONSTANT_NAME', $class_constants)) {
    $constant_value = $class_constants['CONSTANT_NAME'];
} else {
    $constant_value = null;
}

ReflectionClassConstant

[PHP >= 7.1.0]

$class_name = get_class($object); // fully-qualified class name
try {
    $constant_reflex = new \ReflectionClassConstant($class_name, 'CONSTANT_NAME');
    $constant_value = $constant_reflex->getValue();
} catch (\ReflectionException $e) {
    $constant_value = null;
}

There is no real better way. Depends on your needs and use case.

Kamafeather
  • 8,663
  • 14
  • 69
  • 99
  • Your second example (PHP >= 5), the syntax is incorrect. `$class_constants)I{` should be `$class_constants)){` – Lucas Bustamante May 16 '19 at 18:50
  • Note that `defined()` private note is NOT true for `Trait` trait CAN access private stuff, therefore it can also test and access the constant. (works this way from 7.1 up to 8.1) - https://3v4l.org/NQ1f8 also note you can just do `defined("self::CONSTANT")` (note the quotes `"`) – jave.web Nov 04 '22 at 19:03
11

You can use that function:

function constant_exists($class, $name){
    if(is_string($class)){
        return defined("$class::$name");
    } else if(is_object($class)){
        return defined(get_class($class)."::$name");
    }
    return false;
}

Or alternative version using ReflectionClass

function constant_exists($class, $name) {
    if(is_object($class) || is_string($class)){
        $reflect = new ReflectionClass($class);
        return array_key_exists($name, $reflect->getConstants());
    }
    return false;
}
quant2016
  • 447
  • 4
  • 13
  • If you need to check if constant value exists as one of class constant *values*, use second example with Reflection class, only change `array_key_exists` to `in_array`. – Konrad Gałęzowski Sep 21 '21 at 20:45
1

So I tried this:

$constants = new \ReflectionClass(App\Namespace\ClassName::class);
if ($constants->getConstant('CONSTANT_NAME')){
    // Do this
} else {
    // Do that
}

And it worked fine.

pamekar
  • 729
  • 7
  • 10