Is A Class Constant Set?

<?php

class B {
    const A = 1;
}
$c = "b";


// can't use ??, it is a fatal error
echo B::{$c} ?? '';

// can't use isset() because it is an expression
if (isset(B::{$c})) { echo B::{$c}; }

// Must use defined() as it is a constant
// and then, use the string syntax
if (defined("B::$c")) { echo B::{$c}; }

// This still yields a fatal error, or will check the class constant content
if (defined(B::{$c})) { echo B::{$c}; }

When using a dynamic class constant, it is important to check if the constant is actually defined.

It is not possible to use the coalesce ?? operator, as a non-existent class constant yields a fatal error.

Then, it is not possible to use isset(), because a dynamic class constant is actually an expression. The error message is actually misleading, as the offered solution is not available.

The only solution is to use the defined() method, which is made to check constants. In the case of a class constant, one need to use the string syntax, and should not use the class constant syntax.

See Also

PHP Error Messages

PHP Features

Last updated: 14 July 2026