首頁  >  文章  >  後端開發  >  php 中Enum(枚舉)用法詳解

php 中Enum(枚舉)用法詳解

怪我咯
怪我咯原創
2017-07-14 14:39:0414135瀏覽

枚舉是一個整數常數的集合, 枚舉在日常生活中很常見。

例如表示星期的SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,

SATURDAY, 就是一個列舉。

枚舉的說明與結構和聯合相似, 其形式為:

enum 枚舉名{(枚舉值表)

標識符[=整數常數],

標識符[=整數常數],

...

標識符[=整數常數],

} 枚舉變數;

如果枚舉沒有初始化, 即省掉"=整數常數"時, 則從第一個標識符開始, 依

次給標識符賦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());
}

輸出結果如下:

object(MyEnum)#1 (2) {
 ["value":"Enum":private]=>
 string(2) "Hi"
 ["strict":"Enum":private]=>
 bool(true)
}
object(MyEnum)#1 (2) {
 ["value":"Enum":private]=>
 string(2) "By"
 ["strict":"Enum":private]=>
 bool(true)
}
object(MyEnum)#1 (2) {
 ["value":"Enum":private]=>
 string(2) "By"
 ["strict":"Enum":private]=>
 bool(true)
}
string(27) "Value is not in enum MyEnum"

以上是php 中Enum(枚舉)用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn