I have a simple enumeration class that has some constants defined, but I’d like to have a few static methods provide reflection on the enumeration so a programmer.
Can I ask what keys does this enumeration have?, etc.
I have implemented this and it works as advertised. Great so far, but I’d really like to have a base Enum class, where the implementation for these methods exists and all my Enums can extend this and benefit from it.
Unfortunately when I do that the CLASS magic variable returns the base class and messes up the reflection. What I’d love to have is a function to return the child class but any approach that works is fine by me.
Here’s the class definition:
final class LG_NutritionalValues
{
// ENUMERATION
const Calories = 1;
const Fat = 2;
const Carbohydrates = 3;
const Etc = 999;
public static function is_valid_key ( $value ) {
$reflect = new ReflectionClass ( __CLASS__ );
return in_array ( $value , array_keys( $reflect->getConstants() ) );
}
public static function list_keys() {
$reflect = new ReflectionClass ( __CLASS__ );
return array_keys( $reflect->getConstants() );
}
} // END enum class
Since php 5.3 you can use get_called_class()