Return to Snippet

Revision: 20818
at November 25, 2009 22:04 by benjaminpearson


Initial Code
class Emergency {
  const Fire = 0;
  const Flood = 1;
  const NoMilkInFridge = 2;
}

$value = 0; // this is an example of the data you might have

$refl = new ReflectionClass('Emergency');
$enum = $refl->getConstants(); // returns array. key is string, value is integer.
$key = array_keys($enum, $value);
$name = $key[0]; // you now have "Flood"

Initial URL

                                

Initial Description
Proper enumerations in PHP are hard to come by. This uses a class as a pseudo enumeration. Sometimes you'll want to lookup the string name side of the enum when you have the value (ie, you have "1" and you want the string "Flood").

Initial Title
PHP Enumeration Constant Reflection

Initial Tags
php

Initial Language
PHP