PHP
Published in PHP
avatar

Dynamic class constant and Enum member fetch in PHP 8.3

PHP 8.3 and later support retrieval of class constants and Enum objects using a variable name.

Example:

<?php
class TestClass {
    public const TEST_CONST = 42;
}

$constName = 'TEST_CONST';

echo TestClass::{$constName};

Before PHP 8.3, accessing class constants was not allowed and resulted in a syntax error.

Parse error: syntax error, unexpected token ";", 
expecting "(" in ... on line ...

And the same restriction applied to Enums as well, where it was not possible to retrieve an Enum member dynamically.

Example:

<?php
enum TestEnum: int {
    case MyMember = 42;
}

$enumName = 'MyMember';

echo TestEnum::{$enumName}->value;
Parse error: syntax error, unexpected token "->", 
expecting "(" in ``` on line ```

The only way to access class constants and Enum members before PHP 8.3 was with a function like this.

<?php
echo \constant("TestClass::$constName");
echo \constant("TestEnum::$enumName")->value;

From PHP 8.3 onwards, you can access it directly using the following example code.

<?php
 class TestClass {
    public const MY_CONST = 42;
 }

 $constName = 'MY_CONST';

 echo TestClass::{$constName}; 
 

Enum class:

<?php

enum TestEnum: int {
    case MyMember = 42;
}

$enumName = 'MyMember';
echo TestEnum::{$enumName}->value;

The expression inside the { } is not limited to a variable name. Any expression that returns a value is allowed:

<?php
class TestClass {
    public const MY_CONST = 42;
}

$constPrefix = 'MY_';

echo TestClass::{$constPrefix . 'CONST'};

Comments