I know that PHP doesn\'t have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values whi
My attempt to create an enum with PHP...it's extremely limited since it doesn't support objects as the enum values but still somewhat useful...
class ProtocolsEnum {
const HTTP = '1';
const HTTPS = '2';
const FTP = '3';
/**
* Retrieve an enum value
* @param string $name
* @return string
*/
public static function getValueByName($name) {
return constant('self::'. $name);
}
/**
* Retrieve an enum key name
* @param string $code
* @return string
*/
public static function getNameByValue($code) {
foreach(get_class_constants() as $key => $val) {
if($val == $code) {
return $key;
}
}
}
/**
* Retrieve associate array of all constants (used for creating droplist options)
* @return multitype:
*/
public static function toArray() {
return array_flip(self::get_class_constants());
}
private static function get_class_constants()
{
$reflect = new ReflectionClass(__CLASS__);
return $reflect->getConstants();
}
}