Convert a constant value to its string name in PHP

I ran into a case where I had to get the string representation of a constant based only on its value, so a little digging around and some experimentation produced this:


const MY_CONSTANT = 1;

// get constant name by value
$class = new ReflectionClass('MyClassName');
$constants = array_flip($class->getConstants());

echo $constants[1];

// output is "MY_CONSTANT"

If you’re in an instance method and want to retrieve the constants of the current class, use get_class($this) here for the ReflectionClass constructor argument.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.