Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Class Constants Dynamically in PHP

I want to be able to look up the value of a constant dynamically, but using a variable doesn't work with the syntax.

<?php
class Food {
    const FRUITS = 'apple, banana, orange';
    const VEGETABLES = 'spinach, carrot, celery';
}

$type = 'FRUITS';

echo Food::FRUITS;
echo Food::$type;

?>

gives

apple, banana, orange

Fatal error: Access to undeclared static property: Food::$type

How can I dynamically call the constant?

like image 920
jcropp Avatar asked Aug 07 '26 11:08

jcropp


2 Answers

The only solution which comes to my head is using a constant function:

echo constant('Food::' . $type);

Here you create name of a constant, including class, as a string and pass this string ('Food::FRUITS') to constant function.

like image 179
u_mulder Avatar answered Aug 09 '26 02:08

u_mulder


This will be available natively in php8.3 as of November 2023

class MyClass {
    public const MY_CONST = 42;
}

$constName = 'MY_CONST';

echo MyClass::{$constName};

https://php.watch/versions/8.3/dynamic-class-const-enum-member-syntax-support

like image 36
Luke Manson Avatar answered Aug 09 '26 01:08

Luke Manson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!