Get value of dynamically chosen class constant

04/14/2020 01:30:01

I would like to be able to do something like this:

class ThingIDs
{
    const Something = 1;
    const AnotherThing = 2;
}

$thing = 'Something';
$id = ThingIDs::$thing;

This doesn't work. Is there a straightforward way of doing something equivalent? Note that I'm stuck with the class; it's in a library I can't rewrite. I'm writing code that takes arguments on the command line, and I would really like it to take symbolic names instead of id numbers.

Verified Answer (176 Votes)

05/27/2011 07:20:20

$id = constant("ThingIDs::$thing");

http://php.net/manual/en/function.constant.php

176

Answer #2 (26 Votes)

05/27/2011 07:19:40

Use Reflection

$r = new ReflectionClass('ThingIDs');
$id = $r->getConstant($thing);
26

Answer #3 (12 Votes)

10/07/2014 12:26:00

If you are using namespaces, you should include the namespace with the class.

echo constant('My\Application\ThingClass::ThingConstant'); 
12
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.