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编程语言开发动态WAP页面
Oct 09 PHP
mysq GBKl乱码
Nov 28 PHP
php is_file 判断给定文件名是否为一个正常的文件
May 10 PHP
php站内搜索并高亮显示关键字的实现代码
Dec 29 PHP
php 获取今日、昨日、上周、本月的起始时间戳和结束时间戳的方法
Sep 28 PHP
PHP与MYSQL中UTF8 中文排序示例代码
Oct 23 PHP
php实现webservice实例
Nov 06 PHP
php实现可用于mysql,mssql,pg数据库操作类
Dec 13 PHP
php使用PDO操作MySQL数据库实例
Dec 30 PHP
php上传图片并压缩的实现方法
Dec 22 PHP
php递归函数怎么用才有效
Feb 24 PHP
php和C#的yield迭代器实现方法对比分析
Jul 17 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生成随机数/生成随机字符串的方法小结【5种方法】
2020/05/27 PHP
解决PHPstudy Apache无法启动的问题【亲测有效】
2020/10/30 PHP
Jquery 数据选择插件Pickerbox使用介绍
2012/08/24 Javascript
JS判断浏览器是否支持某一个CSS3属性的方法
2014/10/17 Javascript
JavaScript中判断变量是数组、函数或是对象类型的方法
2015/02/25 Javascript
javascript带回调函数的异步脚本载入方法实例分析
2015/07/02 Javascript
简单纯js实现点击切换TAB标签实例
2015/08/23 Javascript
详解页面滚动值scrollTop在FireFox与Chrome浏览器间的兼容问题
2015/12/03 Javascript
js创建对象的方法汇总
2016/01/07 Javascript
js提示框替代系统alert,自动关闭alert对话框的实现方法
2016/11/07 Javascript
浅谈jQuery操作类数组的工具方法
2016/12/23 Javascript
Vue2路由动画效果的实现代码
2017/07/10 Javascript
Bootstrap滚动监听组件scrollspy.js使用方法详解
2017/07/20 Javascript
AngularJs每天学习之总体介绍
2017/08/07 Javascript
Node.js+jade抓取博客所有文章生成静态html文件的实例
2017/09/19 Javascript
浅谈vue2 单页面如何设置网页title
2017/11/08 Javascript
基于vue2实现上拉加载功能
2017/11/28 Javascript
js中call()和apply()改变指针问题的讲解
2019/01/17 Javascript
利用Dectorator分模块存储Vuex状态的实现
2019/02/05 Javascript
jquery实现聊天机器人
2020/02/08 jQuery
python实现下载整个ftp目录的方法
2017/01/17 Python
基于循环神经网络(RNN)的古诗生成器
2018/03/26 Python
python用opencv批量截取图像指定区域的方法
2019/01/24 Python
Python使用matplotlib实现交换式图形显示功能示例
2019/09/06 Python
Python SQLAlchemy入门教程(基本用法)
2019/11/11 Python
Python timeit模块的使用实践
2020/01/13 Python
python3中的logging记录日志实现过程及封装成类的操作
2020/05/12 Python
物业工作计划书
2014/01/10 职场文书
九年级化学教学反思
2014/01/28 职场文书
管理失职检讨书
2014/02/12 职场文书
志愿者服务感言
2014/02/27 职场文书
党员群众路线承诺书
2014/05/20 职场文书
企业管理标语
2014/06/10 职场文书
先进党支部事迹材料
2014/12/24 职场文书
小学五年级语文上册教学计划
2015/01/22 职场文书
2016年心理学教育培训学习心得体会
2016/01/12 职场文书