Skip to content

Instantly share code, notes, and snippets.

@colinodell
Created August 18, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinodell/511036c22e023eb34c6c to your computer and use it in GitHub Desktop.
Save colinodell/511036c22e023eb34c6c to your computer and use it in GitHub Desktop.
Enum-like class for PHP
<?php
/**
* Base class used to build enums
*/
abstract class AbstractEnum
{
/**
* @var array Options array, suitable for a select box
*/
protected static $optionsArray = array();
/**
* Get human-friendly label for the given enum value
* @param int $val
*
* @return string
*/
public static function getLabel($val)
{
return static::$optionsArray[$val];
}
/**
* Get array of options suitable for a select box
* @return array
*/
public static function getOptionsArray()
{
return static::$optionsArray;
}
/**
* Get all the values
* This is equivalent to the keys of the options array
*
* @return array
*/
public static function getValues()
{
return array_keys(static::$optionsArray);
}
}
<?php
class AuthMethod extends AbstractEnum
{
const AUTH_METHOD_NONE = 'none';
const AUTH_METHOD_BASIC = 'basic';
/**
* @var array Options array, suitable for a select box
*/
protected static $optionsArray = array(
self::AUTH_METHOD_NONE => 'None',
self::AUTH_METHOD_BASIC => 'Basic Authorization',
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment