Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class constant using a simple variable which contains the name of the constant

I'm trying to access a class constant in one of my classes:

const MY_CONST = "value"; 

If I have a variable which holds the name of this constant like this:

$myVar = "MY_CONST"; 

Can I access the value of MY_CONST somehow?

self::$myVar 

does not work obviously because it is for static properties. Variable variables does not work either.

like image 754
Adam Arold Avatar asked Sep 21 '11 20:09

Adam Arold


People also ask

How can I get constant variable in PHP?

If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.

What is the purpose of constant () function?

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

How do you declare a constant in a class in C ++?

To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .


2 Answers

There are two ways to do this: using the constant function or using reflection.

Constant Function

The constant function works with constants declared through define as well as class constants:

class A {     const MY_CONST = 'myval';      static function test()     {         $c = 'MY_CONST';         return constant('self::'. $c);     } }  echo A::test(); // output: myval 

Reflection Class

A second, more laborious way, would be through reflection:

$ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // output: myval 
like image 194
webbiedave Avatar answered Oct 09 '22 13:10

webbiedave


There is no syntax for that, but you can use an explicit lookup:

print constant("classname::$myConst"); 

I believe it also works with self::.

like image 35
mario Avatar answered Oct 09 '22 13:10

mario