ホームページ  >  記事  >  バックエンド開発  >  PHPにおけるEnum(列挙)の使い方を詳しく解説

PHPにおけるEnum(列挙)の使い方を詳しく解説

怪我咯
怪我咯オリジナル
2017-07-14 14:39:0414077ブラウズ

列挙型は整数定数のコレクションであり、日常生活で非常に一般的です。

たとえば、曜日を表すSUNDAY、MONDAY、TUESDAY、WEDNESDAY、THURSDAY、FRIDAY、

SATURDAYは列挙型です。

列挙型の記述は構造体や共用体と似ており、その形式は次のとおりです:

enum 列挙型名 {(列挙値テーブル)

identifier [= 整数定数],

identifier [= 整数定数] ,

...

識別子 [=整数定数],

} 列挙型変数;

列挙型が初期化されていない場合、つまり「=整数定数」が省略されている場合、最初の識別子に 0、1、2 を代入して開始します。 、 ... 識別子に

回。ただし、列挙値テーブル内のメンバーに値が割り当てられると、後続のメンバーは順番に 1 を加算する規則に従って値を決定します。

この記事の例では、PHP での Enum (列挙) の使用法について説明します。参考のために皆さんと共有してください。詳細は次のとおりです:

PHP には実際には Enum クラス ライブラリがあり、これには Perl 拡張機能のインストールが必要です。したがって、PHP の標準拡張機能ではないため、コードの実装には実行中のphp環境のサポート。

(1) クラスライブラリSplEnumクラスを拡張します。このクラスの概要は以下の通りです。

SplEnum extends SplType {
/* Constants */
const NULL default = null ;
/* 方法 */
public array getConstList ([ bool $include_default = false ] )
/* 继承的方法 */
SplType::construct ([ mixed $initial_value [, bool $strict ]] )
}

使用例

:

<?php
class Month extends SplEnum {
  const default = self::January;
  const January = 1;
  const February = 2;
  const March = 3;
  const April = 4;
  const May = 5;
  const June = 6;
  const July = 7;
  const August = 8;
  const September = 9;
  const October = 10;
  const November = 11;
  const December = 12;
}
echo new Month(Month::June) . PHP_EOL;
try {
  new Month(13);
} catch (UnexpectedValueException $uve) {
  echo $uve->getMessage() . PHP_EOL;
}
?>
出力結果:

6
Value not a const in enum Month

(2) カスタマイズされたEnumクラスライブラリ

<?php
/**
 * Abstract class that enables creation of PHP enums. All you
 * have to do is extend this class and define some constants.
 * Enum is an object with value from on of those constants
 * (or from on of superclass if any). There is also
 * default constat that enables you creation of object
 * without passing enum value.
 *
 * @author Marijan Šuflaj <msufflaj32@gmail.com&gt
 * @link http://php4every1.com
 */
abstract class Enum {
  /**
   * Constant with default value for creating enum object
   */
  const default = null;
  private $value;
  private $strict;
  private static $constants = array();
  /**
   * Returns list of all defined constants in enum class.
   * Constants value are enum values.
   *
   * @param bool $includeDefault If true, default value is included into return
   * @return array Array with constant values
   */
  public function getConstList($includeDefault = false) {
    $class = get_class($this);
    if (!array_key_exists($class, self::$constants)) {
      self::populateConstants();
    }
    return $includeDefault ? array_merge(self::$constants[CLASS_], array(
      "default" => self::default
    )) : self::$constants[CLASS_];
  }
  /**
   * Creates new enum object. If child class overrides construct(),
   * it is required to call parent::construct() in order for this
   * class to work as expected.
   *
   * @param mixed $initialValue Any value that is exists in defined constants
   * @param bool $strict If set to true, type and value must be equal
   * @throws UnexpectedValueException If value is not valid enum value
   */
  public function construct($initialValue = null, $strict = true) {
    $class = get_class($this);
    if (!array_key_exists($class, self::$constants)) {
      self::populateConstants();
    }
    if ($initialValue === null) {
      $initialValue = self::$constants[$class]["default"];
    }
    $temp = self::$constants[$class];
    if (!in_array($initialValue, $temp, $strict)) {
      throw new UnexpectedValueException("Value is not in enum " . $class);
    }
    $this->value = $initialValue;
    $this->strict = $strict;
  }
  private function populateConstants() {
    $class = get_class($this);
    $r = new ReflectionClass($class);
    $constants = $r->getConstants();
    self::$constants = array(
      $class => $constants
    );
  }
  /**
   * Returns string representation of an enum. Defaults to
   * value casted to string.
   *
   * @return string String representation of this enum&#39;s value
   */
  public function toString() {
    return (string) $this->value;
  }
  /**
   * Checks if two enums are equal. Only value is checked, not class type also.
   * If enum was created with $strict = true, then strict comparison applies
   * here also.
   *
   * @return bool True if enums are equal
   */
  public function equals($object) {
    if (!($object instanceof Enum)) {
      return false;
    }
    return $this->strict ? ($this->value === $object->value)
      : ($this->value == $object->value);
  }
}

使用例は以下のとおりです:

class MyEnum extends Enum {
  const HI = "Hi";
  const BY = "By";
  const NUMBER = 1;
  const default = self::BY;
}
var_dump(new MyEnum(MyEnum::HI));
var_dump(new MyEnum(MyEnum::BY));
//Use default
var_dump(new MyEnum());
try {
  new MyEnum("I don&#39;t exist");
} catch (UnexpectedValueException $e) {
  var_dump($e->getMessage());
}

出力結果は以下のとおりです:

りー

以上がPHPにおけるEnum(列挙)の使い方を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。