define ('COLOR_RED', 'F00');
define ('COLOR_GREEN', '0F0');
define ('COLOR_BLUE', '00F');
// this variable is FORBIDDEN to modify
$ colors = array (
'red' => 'F00',
'green' => '0F0',
'blue' => '00F',
);
abstract class Enum {
private $ current_val;
final public function __construct ($ type) {
$ class_name = get_class ($ this);
$ type = strtoupper ($ type);
if (constant ("{$ class_name} :: {$ type}") === NULL) {
throw new Enum_Exception ('Properties'. $ type. 'in the enumeration'. $ class_name. 'not found.');
}
$ this-> current_val = constant ("{$ class_name} :: {$ type}");
}
final public function __toString () {
return $ this-> current_val;
}
}
class Enum_Exception extends Exception {}
class Enum_Colors extends Enum {
const RED = 'F00';
const GREEN = '0F0';
const BLUE = '00F';
}
function setColor (Enum_Colors $ color) {
echo $ color;
}
setColor (new Enum_Colors ('GREEN')); // will pass
setColor ('0F0'); // won't pass
Enum_Colors :: RED == new Enum_Colors ('GREEN'); // FALSE
Enum_Colors :: RED == new Enum_Colors ('RED'); // TRUE
public static method asArray() {}
Source: https://habr.com/ru/post/38584/
All Articles