yaomint 发表于 2017-12-29 17:41:26

对于PHP中enum的好奇

<?php  interface enum
  {
  }
  /**
  * @method enum RED() Description
  */

  final>  {
  private static $enums =
[
  'RED' => ,
  'BLUE' => ,
  'BLACK' => ,
  'YELLOW' => ,
  'GREEN' =>
  ];
  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');
页: [1]
查看完整版本: 对于PHP中enum的好奇