Get class constant names in php?

user151841 picture user151841 · May 18, 2010 · Viewed 7.9k times · Source

I have a php class with some class constants that indicate the status of an instance.

When I'm using the class, after I run some methods on it, I do some checks to make sure that the status is what I expect it to be.

For instance, after calling some methods, I expect the status to be MEANINGFUL_STATUS_NAME.

$objInstance->method1();
$objInstance->method2();
if ( $objInstance->status !==  class::MEANINGFUL_STATUS_NAME ) { 
    throw new Exception("Status is wrong, should not be " . class::MEANINGFUL_STATUS_NAME . ".");
}

However, this gives me the exception message

"Status is wrong, should not be 2"

when what I really want to see is

"Status is wrong, should not be MEANINGFUL_STATUS_NAME"

So I've lost the meaningfulness of the constant name. I was thinking of making an 'translation table' array, so I can take the constant values and translate them back into their name, but this seems cumbersome. How should I translate this back, so I get an error message that gives me a better idea of what went wrong?

Answer

Zsolti picture Zsolti · May 18, 2010

This is kind of tricky solution:

$r = new ReflectionClass("YourClassName");
$constantNames = array_flip($r->getConstants());

$objInstance->method1();   
$objInstance->method2();   
if ( $objInstance->status !== YourClassName::MEANINGFUL_STATUS_NAME ) {    
    throw new Exception("Status is wrong, should not be " . $constantNames[YourClassName::MEANINGFUL_STATUS_NAME] . ".");   
}