Get Class Constant Dynamically in PHP 8.3

Get Class Constant Dynamically in PHP 8.3

Before PHP 8.3, the only way to fetch class constants was through the constant function. This function is employed to obtain the value of a constant when its name is unknown, such as when it is stored in a variable or returned by a function.

Let's say we have the following class:

PaginatorConst.php

<?php class PaginatorConst { public const int PER_PAGE = 20; }

We can use the constant function to obtain the value of a constant in the following manner:

<?php require_once 'PaginatorConst.php'; $name = 'PER_PAGE'; echo constant(PaginatorConst::class.'::'.$name); // 20

Since PHP 8.3, it is possible to dynamically get the value of a class constant using syntax ClassName::{$varName}.

<?php require_once 'PaginatorConst.php'; $name = 'PER_PAGE'; echo PaginatorConst::{$name}; // 20

The new syntax works for getting enum cases as well.

UserStatus.php

<?php enum UserStatus: string { case ACTIVE = 'A'; }
<?php require_once 'UserStatus.php'; $name = 'ACTIVE'; echo UserStatus::{$name}->value; // A

Leave a Comment

Cancel reply

Your email address will not be published.