Check if a class constant exists

后端 未结 4 1325
醉梦人生
醉梦人生 2021-02-06 20:43

How can I check if a constant is defined in a PHP class?

class Foo {
    const BAR = 1;
}

Is there something like property_exists()

4条回答
  •  孤独总比滥情好
    2021-02-06 20:51

    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;
    

    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.

提交回复
热议问题