PHP中Enum(枚举)用法实例详解


Posted in PHP onDecember 07, 2015

本文实例讲述了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>
 * @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'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'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程序设计有所帮助。

PHP 相关文章推荐
生成静态页面的PHP类
Nov 25 PHP
php 中文处理函数集合
Aug 27 PHP
PHP操作数组相关函数
Feb 03 PHP
在WAMP环境下搭建ZendDebugger php调试工具的方法
Jul 18 PHP
简单实用的.net DataTable导出Execl
Oct 28 PHP
php preg_replace替换实例讲解
Nov 04 PHP
php实例分享之二维数组排序
May 15 PHP
php堆排序实现原理与应用方法
Jan 03 PHP
浅谈php自定义错误日志
Feb 13 PHP
PHP实现网站应用微信登录功能详解
Apr 11 PHP
浅析PHP echo 和 print 语句
Jun 30 PHP
aec加密 php_php aes加密解密类(兼容php5、php7)
Mar 14 PHP
PHP使用内置函数file_put_contents写入文件及追加内容的方法
Dec 07 #PHP
学习php设计模式 php实现门面模式(Facade)
Dec 07 #PHP
php实现smarty模板无限极分类的方法
Dec 07 #PHP
学习php设计模式 php实现单例模式(singleton)
Dec 07 #PHP
学习php设计模式 php实现桥梁模式(bridge)
Dec 07 #PHP
学习php设计模式 php实现装饰器模式(decorator)
Dec 07 #PHP
PHP函数func_num_args用法实例分析
Dec 07 #PHP
You might like
php函数之子字符串替换&amp;#65279; str_replace
2011/03/23 PHP
PHP求小于1000的所有水仙花数的代码
2012/01/10 PHP
php缩小png图片不损失透明色的解决方法
2013/12/25 PHP
设置php页面编码的两种方法示例介绍
2014/03/03 PHP
php自动给网址加上链接的方法
2015/06/02 PHP
根据一段代码浅谈Javascript闭包
2010/12/14 Javascript
关于JAVASCRIPT urldecode URL解码的问题
2012/01/08 Javascript
js之事件冒泡和事件捕获详细介绍
2013/10/28 Javascript
jquery隔行换色效果实现方法
2015/01/15 Javascript
JavaScript实现模仿桌面窗口的方法
2015/07/18 Javascript
javascript高级选择器querySelector和querySelectorAll全面解析
2016/04/07 Javascript
深入理解JS中的substr和substring
2016/04/26 Javascript
使用微信内嵌H5网页解决JS倒计时失效问题
2017/01/13 Javascript
Vue组件通信实践记录(推荐)
2017/08/15 Javascript
Vue.js实现表格渲染的方法
2018/09/07 Javascript
react+ant design实现Table的增、删、改的示例代码
2018/12/27 Javascript
详解puppeteer使用代理
2018/12/27 Javascript
jQuery 筛选器简单操作示例
2019/10/02 jQuery
微信小程序swiper左右扩展各显示一半代码实例
2019/12/05 Javascript
微信小程序swiper使用网络图片不显示问题解决
2019/12/13 Javascript
[56:12]LGD vs Optic Supermajor小组赛D组胜者组决赛 BO3 第一场 6.3
2018/06/04 DOTA
[45:18]完美世界DOTA2联赛循环赛 PXG vs IO 第二场 11.06
2020/11/09 DOTA
Python实现的HMacMD5加密算法示例
2018/04/03 Python
Django实现全文检索的方法(支持中文)
2018/05/14 Python
python设置环境变量的原因和方法
2019/06/24 Python
python networkx 根据图的权重画图实现
2019/07/10 Python
python 如何去除字符串头尾的多余符号
2019/11/19 Python
sklearn和keras的数据切分与交叉验证的实例详解
2020/06/19 Python
Python获取excel内容及相关操作代码实例
2020/08/10 Python
如何在python中实现线性回归
2020/08/10 Python
html5的websockets全双工通信详解学习示例
2014/02/26 HTML / CSS
优秀员工年终发言演讲稿
2014/01/01 职场文书
关工委先进个人事迹材料
2014/05/23 职场文书
个人总结怎么写
2015/02/26 职场文书
Python基础知识之变量的详解
2021/04/14 Python
教你做个可爱的css滑动导航条
2021/06/15 HTML / CSS