Get value of dynamically chosen class constant in PHP

Ben picture Ben · May 27, 2011 · Viewed 30.2k times · Source

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.

Answer

Dan Simon picture Dan Simon · May 27, 2011

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

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