Let's say I have a class like so:
class Order {
const STATUS_INITIALIZED = 'initialized';
const STATUS_ORDERED = 'ordered';
}
and I'd like to grab the constant like so:
$status = $_GET['status']; // ?status=STATUS_ORDERED
Is there a way to access the value of the constant, given the name of the constant as a string?
I've tried:
Order::$status
Order::$$status
A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Unfortunately, this means you cannot use the const keyword within conditional statements. Like using the define() function, you should write the constant name in uppercase letters or numbers. The basic syntax for using the const keyword to define a constant in PHP is as we have shown it below.
The constant() function returns the value of a constant. Note: This function also works with class constants.
The function constant
does this. The syntax is
constant('Order::'.$status)
See it in action.
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