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 不同编码下的字符串长度区分
Sep 26 PHP
PHP取得一个类的属性和方法的实现代码
May 22 PHP
配置php网页显示各种语法错误
Sep 23 PHP
PHP+jQuery 注册模块开发详解
Oct 14 PHP
php隐藏IP地址后两位显示为星号的方法
Nov 21 PHP
PHP使用pcntl_fork实现多进程下载图片的方法
Dec 16 PHP
Zend Framework使用Zend_Loader组件动态加载文件和类用法详解
Dec 09 PHP
使用PHP连接多种数据库的实现代码(mysql,access,sqlserver,Oracle)
Dec 21 PHP
php获取给定日期相差天数的方法分析
Feb 20 PHP
php实现的统计字数函数定义与使用示例
Jul 26 PHP
thinkphp5框架扩展redis类方法示例
May 06 PHP
Thinkphp5.0 框架使用模型Model添加、更新、删除数据操作详解
Oct 11 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
MySql中正则表达式的使用方法描述
2008/07/30 PHP
php读取mysql的简单实例
2014/01/15 PHP
php 使用html5 XHR2实现上传文件与进度显示功能示例
2020/03/03 PHP
javascript 日期时间函数(经典+完善+实用)
2009/05/27 Javascript
js时间日期格式化封装函数
2014/12/02 Javascript
简介JavaScript中strike()方法的使用
2015/06/08 Javascript
jQuery实现在最后一个元素之前插入新元素的方法
2015/07/18 Javascript
WEB前端开发都应知道的jquery小技巧及jquery三个简写
2015/11/15 Javascript
js判断当前页面用什么浏览器打开的方法
2016/01/06 Javascript
Jquery中巧用Ajax的beforeSend方法
2016/01/20 Javascript
jQuery ajax分页插件实例代码
2016/01/27 Javascript
一个用jquery写的判断div滚动条到底部的方法【推荐】
2016/04/29 Javascript
Js获取图片原始宽高的实现代码
2016/05/17 Javascript
AngularJS使用ng-repeat和ng-if实现数据的删选显示效果示例【适用于表单数据的显示】
2016/12/13 Javascript
JS基于递归算法实现1,2,3,4,5,6,7,8,9倒序放入数组中的方法
2017/01/03 Javascript
详解使用React进行组件库开发
2018/02/06 Javascript
代码实例ajax实现点击加载更多数据图片
2018/10/12 Javascript
深入解析ES6中的promise
2018/11/08 Javascript
js实现通过开始结束控制的计时器
2019/02/25 Javascript
JS eval代码快速解密实例解析
2020/04/23 Javascript
Sublime Text3 配置 NodeJs 环境的方法
2020/05/20 NodeJs
vue element实现表格合并行数据
2020/11/30 Vue.js
vue-calendar-component 封装多日期选择组件的实例代码
2020/12/04 Vue.js
[01:24:51]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS NewBee第二场
2014/05/26 DOTA
Python3.x和Python2.x的区别介绍
2013/02/12 Python
python发送邮件功能实现代码
2016/07/15 Python
利用python实现简单的循环购物车功能示例代码
2017/07/05 Python
python生成ppt的方法
2018/06/07 Python
对python:threading.Thread类的使用方法详解
2019/01/31 Python
python中的列表与元组的使用
2019/08/08 Python
Python ORM编程基础示例
2020/02/02 Python
地图可视化神器kepler.gl python接口的使用方法
2020/12/22 Python
Myprotein瑞典官方网站:畅销欧洲英国运动营养品牌
2018/01/22 全球购物
简历的自荐信
2013/12/19 职场文书
2015年秘书个人工作总结
2015/04/25 职场文书
交通安全教育主题班会
2015/08/12 职场文书