Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of the constant?

Assuming you have a constant defined in a class:

class Foo {     const ERR_SOME_CONST = 6001;      function bar() {         $x = 6001;         // need to get 'ERR_SOME_CONST'     } } 

Is it possible with PHP?

like image 688
Deniss Kozlovs Avatar asked Dec 10 '09 10:12

Deniss Kozlovs


People also ask

What are constants in a name?

Examples of constant names are VAT and COMPUTER_NAME . Constant names are not case sensitive, which means there is no difference between uppercase and lowercase characters. For example, the myCONST , myconts , MYCONST , and MyConst names are actually referring to the same constant. No space characters are allowed.

How do you name a constant in Java?

Syntax to assign a constant value in java:static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded. The final modifier makes the variable unchangeable.

How do you name a constant in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.


1 Answers

You can get them with the reflection API

I'm assuming you would like to get the name of the constant based on the value of your variable (value of variable == value of constant). Get all the constants defined in the class, loop over them and compare the values of those constants with the value of your variable. Note that with this approach you might get some other constant that the one you want, if there are two constants with the same value.

example:

class Foo {     const ERR_SOME_CONST = 6001;     const ERR_SOME_OTHER_CONST = 5001;      function bar() {         $x = 6001;         $fooClass = new ReflectionClass ( 'Foo' );         $constants = $fooClass->getConstants();          $constName = null;         foreach ( $constants as $name => $value )         {             if ( $value == $x )             {                 $constName = $name;                 break;             }         }          echo $constName;     } } 

ps: do you mind telling why you need this, as it seems very unusual ...

like image 114
Jan Hančič Avatar answered Sep 17 '22 12:09

Jan Hančič