Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a class const dynamically in PHP?

Tags:

php

constants

get

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
like image 876
Andrew Avatar asked Jan 17 '12 23:01

Andrew


People also ask

How do you call a class constant in PHP?

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.

Can we declare constants in PHP by using below syntax $constant?

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.

What is the purpose of constant () function?

The constant() function returns the value of a constant. Note: This function also works with class constants.


1 Answers

The function constant does this. The syntax is

constant('Order::'.$status)

See it in action.

like image 189
Jon Avatar answered Oct 01 '22 18:10

Jon