Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

A new syntax is available since version 8.3 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};

?>

Documentation

See Also