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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With