Get class constant names in php?
I have a php class with some class constants that indicate the status of the instance.
When I use the class, after running some methods, I do some checks to make sure the status is what I expect.
For example, 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 an exception message
"Status is wrong, should not be 2"
when i really want to see
"Status is wrong, should not be MEANINGFUL_STATUS_NAME"
So, I lost the meaning of the permanent name. I was thinking about creating an array "translation table" so I can take constant values and translate them back into their name, but that seems cumbersome. How do I translate this back so I get an error that gives me a better idea of what went wrong?
a source to share
This is a rather 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] . ".");
}
a source to share
Another way is to let the object check if the status is in the desired mode.
If it is not, the object's method may throw an exception.
Unadorned example:
class Klasse
{
const WANTED_VALUE = 1;
const UNWANTED_VALUE = 2;
private static $constant_names = array();
p... function __construct ()
{
if ( empty( self::$constant_names ) )
{
$class = new ReflectionClass( __CLASS__ );
$constants = $class->getConstants();
$constants = array_flip( $constants );// requires the constant values to be unique
self::$constants = $constants;
}
}
public function checkNeededStatus ()
{
$needed_status = self::WANTED_VALUE;// could also be a parameter(an argument) with a default value
if ( $this->status !== $needed_status )
{
$constant_name = self::$constants[ $this->status ];
$message = 'Status is wrong, '
. 'should not be: `' . $constant_name . '`.'
;
//$message .= '(it should be `' . self::$constants[ $needed_status ] . '`)';
throw new Exception( $message );
}
}
}
$objInstance = new Klasse();
$objInstance->method1();
$objInstance->method2();
$objInstance->checkNeededStatus();
credit:
It might be a good idea to consider using Reflection. As the thrown message remains within the class, it becomes more likely to occur without losing significant maintainability.
a source to share