Dynamic Class Constant

Dynamic class constant access has always been possible with a call to the constant() function. With the class::constant syntax, it is possible to reach any visible constant, or, also, enumeration cases.

In PHP 8.3, a new syntax is available to do the same: class::{$name}. The curly braces are important in that call.

<?php

enum E: string {
    case A = 'abc';
    const B = 'def';
}

$name = 'E::A';
echo constant($name)->value;
// PHP 8.3+
echo E::{$name}->value;

$name = 'E::B';
echo constant($name);
// PHP 8.3+
echo E::{$name};

?>

See also PHP 8.3: Dynamic class constant and Enum member fetch support.

Related : Static Constant, Constants, Dynamic, Enumeration (enum), Functions, constant()