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 相关文章推荐
fleaphp crud操作之find函数的使用方法
Apr 23 PHP
php中判断文件存在是用file_exists还是is_file的整理
Sep 12 PHP
通过table标签,PHP输出EXCEL的实现方法
Jul 24 PHP
PHP中判断变量为空的几种方法小结
Nov 12 PHP
PHP遍历并打印指定目录下所有文件实例
Feb 10 PHP
php根据日期判断星座的函数分享
Feb 13 PHP
Php无限级栏目分类读取的实现代码
Feb 19 PHP
html静态页面调用php文件的方法
Nov 13 PHP
PHP图片裁剪与缩放示例(无损裁剪图片)
Feb 08 PHP
PHP/ThinkPHP实现批量打包下载文件的方法示例
Jul 31 PHP
浅谈PHP封装CURL
Mar 06 PHP
PHP使用 Pear 进行安装和卸载包的方法详解
Jul 08 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 XPath对XML文件查找及修改实现代码
2011/07/27 PHP
php中定时计划任务的实现原理
2013/01/08 PHP
PHP中PDO的事务处理分析
2016/04/07 PHP
ExtJS 2.0实用简明教程 之Ext类库简介
2009/04/29 Javascript
js获取当前月的第一天和最后一天的小例子
2013/11/18 Javascript
js获取当前路径的简单示例代码
2014/01/08 Javascript
原生js实现淘宝首页点击按钮缓慢回到顶部效果
2014/04/06 Javascript
用html+css+js实现的一个简单的图片切换特效
2014/05/28 Javascript
超级简单的jquery操作表格方法
2014/12/15 Javascript
Bootstrap3 多选和单选框(checkbox)
2016/12/29 Javascript
深入浅析AngularJs模版与v-bind
2018/07/06 Javascript
JS 正则表达式验证密码、邮箱格式的实例代码
2018/10/28 Javascript
js实现倒计时器自定义时间和暂停
2019/02/25 Javascript
vue.js实现三级菜单效果
2019/10/19 Javascript
electron+vue实现div contenteditable截图功能
2020/01/07 Javascript
vue实现桌面向网页拖动文件的示例代码(可显示图片/音频/视频)
2021/03/01 Vue.js
解决Python 爬虫URL中存在中文或特殊符号无法请求的问题
2018/05/11 Python
python实现批量解析邮件并下载附件
2018/06/19 Python
python selenium 获取标签的属性值、内容、状态方法
2018/06/22 Python
python 正确保留多位小数的实例
2018/07/16 Python
在Python 不同级目录之间模块的调用方法
2019/01/19 Python
Python正则表达式匹配日期与时间的方法
2019/07/07 Python
Flask框架中request、请求钩子、上下文用法分析
2019/07/23 Python
python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例
2020/03/10 Python
python实现数字炸弹游戏程序
2020/07/17 Python
python线程优先级队列知识点总结
2021/02/28 Python
暇步士官网:Hush Puppies
2016/09/22 全球购物
英国当代时尚和街头服饰店:18montrose
2018/12/15 全球购物
市场开发计划书
2014/05/07 职场文书
2014年司机工作总结
2014/11/21 职场文书
初中差生评语
2014/12/29 职场文书
法律服务所工作总结
2015/08/10 职场文书
关于公司年会的开幕词
2016/03/04 职场文书
用Python爬取英雄联盟的皮肤详细示例
2021/12/06 Python
Window server 2012 R2 AD域的组策略相关设置
2022/04/28 Servers
从原生JavaScript到React深入理解
2022/07/23 Javascript