|
<?php interface enum
{
}
/**
* @method enum RED() Description
*/
final> {
private static $enums =
[
'RED' => [255, 0, 0],
'BLUE' => [0, 0, 255],
'BLACK' => [0, 0, 0],
'YELLOW' => [255, 255, 0],
'GREEN' => [0, 255, 0]
];
private static $objs = [];
private $name;
public static function __callStatic($name, $arguments)
{
if (!array_key_exists($name, static::$enums)) {
throw new Exception('enum not existed', -1);
}
return static::valueOf($name);
}
private function setName($val): void
{
$this->name = $val;
}
private static function initEnum(string $name): bool
{
if (isset(static::$objs[$name])) {
return true;
}
if (!array_key_exists($name, static::$enums)) {
throw new Exception('enum not existed', -1);
}
$obj = new Color();
$obj->setName($name);
static::$objs[$name] = $obj;
return true;
}
public static function values(): array
{
if (empty(static::$objs)) {
foreach (array_keys(static::$enums) as $name) {
static::initEnum($name);
}
}
return static::$objs;
}
public static function valueOf(string $name): enum
{
if (!array_key_exists($name, static::$enums)) {
throw new Exception('enum not existed', -1);
}
static::initEnum($name);
return static::$objs[$name];
}
public function ordinal(): int
{
//TODO
return 0;
}
/**
* @throws> */
public function compareTo(enum $other): int
{
//TODO
return -1;
}
public function equals(enum $other): bool
{
//TODO
return true;
}
public function __toString()
{
if (!$this->name) {
return '';
}
return '(' . implode(',', static::$enums[$this->name]) . ')';
}
}
echo (string) Color::RED();
echo (string) Color::valueOf('BLACK'); |
|
|