Skip to content

Instantly share code, notes, and snippets.

@fragoulis
Last active August 29, 2015 14:04
Show Gist options
  • Save fragoulis/60c69f6a82d338f63d51 to your computer and use it in GitHub Desktop.
Save fragoulis/60c69f6a82d338f63d51 to your computer and use it in GitHub Desktop.
PHP Enumeration implementation
<?php
/**
* Enumeration base class.
*
* Clients can implement this to create commonly used enum
* structs with the use of CONSTs.
*
* Example:
* <pre>
* class Fruit extends Enumeration
* {
* const APPLE=1;
* const ORANGE=2;
*
* static function labels()
* {
* return [
* self::APPLE=>'Apple',
* self::ORANGE=>'Orange',
* ];
* }
* }
* <pre>
*
* To easily use in drop down lists and in key=>value pairs in
* general where you want value to be a readable and translatable
* label, implement the {@link labels} method which should return
* an array of pairs like above.
*
* @author John Fragkoulis <john.fragkoulis@gmail.com>
* @since 0.5
*/
abstract class Enum implements EnumInterface
{
protected static $_constants;
/**
* @return array the array of constants in contant=>value pairs.
*/
public static function toArray()
{
$className=get_called_class();
if(self::$_constants===null || !isset(self::$_constants[$className])) {
$class=new ReflectionClass($className);
self::$_constants[$className]=$class->getConstants();
}
return self::$_constants[$className];
}
/**
* @return array an array of the constants.
*/
public static function keys()
{
return array_keys(static::toArray());
}
/**
* @return array the array of the constants in contant=>label pairs.
* @throws CException if used without being implemented by overriding
* class.
*/
public static function labels()
{
return array_combine(static::toArray(), static::toArray());
}
/**
* @param mixed $constant
* @return string the label assigned to a specific constant.
*/
public static function label($constant)
{
$labels=static::labels();
return $labels[$constant];
}
}
<?php
interface EnumInterface
{
public static function toArray();
public static function keys();
public static function labels();
public static function label($constant);
}
@fragoulis
Copy link
Author

Another approach would be to implement the interface functionality inside a trait called EnumTrait.php and use that trait in your enum class. as such:

class MyEnum implements EnumInterface
{
    use EnumTrait;

    ....
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment