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编程开发“虚拟域名”系统
Oct 09 PHP
在线短消息收发的程序,不用数据库
Oct 09 PHP
探讨PHP删除文件夹的三种方法
Jun 09 PHP
解析PHP将对象转换成数组的方法(兼容多维数组类型)
Jun 21 PHP
php使用filter过滤器验证邮箱 ipv6地址 url验证
Dec 25 PHP
php代码审计比较有意思的例子
May 07 PHP
joomla实现注册用户添加新字段的方法
May 05 PHP
thinkphp 字母函数详解T/I/N/D/M/A/R/U
Apr 03 PHP
PHP实现的注册,登录及查询用户资料功能API接口示例
Jun 06 PHP
PHP微信公众号开发之微信红包实现方法分析
Jul 14 PHP
PHP验证码无法显示的原因及解决办法
Aug 11 PHP
PHP PDOStatement::rowCount讲解
Feb 01 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环境搭建的详细步骤
2016/06/30 PHP
jQuery实现表单input中提示文字value随鼠标焦点移进移出而显示或隐藏的代码
2010/03/21 Javascript
js文件缓存之版本管理详解
2013/07/05 Javascript
BOOTSTRAP时间控件显示在模态框下面的bug修复
2015/02/05 Javascript
iScroll中事件点击触发两次解决方案
2015/03/11 Javascript
SWFObject基本用法实例分析
2015/07/20 Javascript
jquery实现简单的全选和反选功能
2016/01/02 Javascript
学习javascript面向对象 掌握创建对象的9种方式
2016/01/04 Javascript
简单谈谈javascript中this的隐式绑定
2016/02/22 Javascript
浅谈JS封闭函数、闭包、内置对象
2017/07/18 Javascript
AngularJS实现的输入框字数限制提醒功能示例
2017/10/26 Javascript
Vue2.0设置全局样式(less/sass和css)
2017/11/18 Javascript
JS排序算法之希尔排序与快速排序实现方法
2017/12/12 Javascript
使用vue-cli创建项目的图文教程(新手入门篇)
2018/05/02 Javascript
微信小程序实现省市区三级地址选择
2020/06/21 Javascript
JS实现二维数组元素的排列组合运算简单示例
2019/01/28 Javascript
通过实例讲解JS如何防抖动
2019/06/15 Javascript
vue实现表单录入小案例
2019/09/27 Javascript
浅谈vant组件Picker 选择器选单选问题
2020/11/04 Javascript
Vue如何实现变量表达式选择器
2021/02/18 Vue.js
[01:05:40]VG vs Newbee 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
Python的Bottle框架中返回静态文件和JSON对象的方法
2015/04/30 Python
Python序列化基础知识(json/pickle)
2017/10/19 Python
python版opencv摄像头人脸实时检测方法
2018/08/03 Python
Django添加feeds功能的示例
2018/08/07 Python
python模块和包的应用BASE_PATH使用解析
2019/12/14 Python
Python requests模块安装及使用教程图解
2020/06/30 Python
雅诗兰黛旗下走天然植物路线的彩妆品牌:Prescriptives
2016/08/14 全球购物
小蚁科技官方商店:YI Technology
2019/08/23 全球购物
创联软件面试题笔试题
2012/10/07 面试题
甜品店的创业计划书范文
2014/01/02 职场文书
离婚协议书范本(2014版)
2014/09/28 职场文书
社会实践活动报告
2015/02/05 职场文书
给朋友的道歉短信
2015/05/12 职场文书
Python 制作自动化翻译工具
2021/04/25 Python
使用Python解决图表与画布的间距问题
2022/04/11 Python