PHP Enumeration Constant Reflection


/ Published in: PHP
Save to your folder(s)

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").


Copy this code and paste it in your HTML
  1. class Emergency {
  2. const Fire = 0;
  3. const Flood = 1;
  4. const NoMilkInFridge = 2;
  5. }
  6.  
  7. $value = 0; // this is an example of the data you might have
  8.  
  9. $refl = new ReflectionClass('Emergency');
  10. $enum = $refl->getConstants(); // returns array. key is string, value is integer.
  11. $key = array_keys($enum, $value);
  12. $name = $key[0]; // you now have "Flood"

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.