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 06 PHP
php实现mysql事务处理的方法
Dec 25 PHP
PHP判断IP并转跳到相应城市分站的方法
Mar 25 PHP
CI框架源码解读之URI.php中_fetch_uri_string()函数用法分析
May 18 PHP
PHP封装返回Ajax字符串和JSON数组的方法
Feb 17 PHP
PHP给源代码加密的几种方法汇总(推荐)
Feb 06 PHP
PHP仿tp实现mvc框架基本设计思路与实现方法分析
May 23 PHP
PHP基于curl模拟post提交json数据示例
Jun 22 PHP
PHP通过get方法获得form表单数据方法总结
Sep 12 PHP
Laravel Eloquent分表方法并使用模型关联的实现
Nov 25 PHP
php7 图形用户界面GUI 开发示例
Feb 22 PHP
PHP sdk实现在线打包代码示例
Dec 09 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 读取文件乱码问题
2010/02/20 PHP
php判断页面是否是微信打开的示例(微信打开网页)
2014/04/25 PHP
PHP ajax 异步执行不等待执行结果的处理方法
2015/05/27 PHP
PHPExcel实现表格导出功能示例【带有多个工作sheet】
2018/06/13 PHP
JavaScript可否多线程? 深入理解JavaScript定时机制
2012/05/23 Javascript
JS操作JSON要领详细总结
2013/08/25 Javascript
SeaJS入门教程系列之SeaJS介绍(一)
2014/03/03 Javascript
javascript实现多栏闭合展开式广告位菜单效果实例
2015/08/05 Javascript
js全选按钮的实现方法
2015/11/17 Javascript
JS模拟简易滚动条效果代码(附demo源码)
2016/04/05 Javascript
AngularJS中实现动画效果的方法
2016/07/28 Javascript
bootstrap选项卡使用方法解析
2017/01/11 Javascript
浅谈jQuery中的$.extend方法来扩展JSON对象
2017/02/12 Javascript
Vue学习笔记进阶篇之vue-router安装及使用方法
2017/07/19 Javascript
vue如何集成raphael.js中国地图的方法示例
2017/08/15 Javascript
bootstrap confirmation按钮提示组件使用详解
2017/08/22 Javascript
JS设计模式之状态模式概念与用法分析
2018/02/05 Javascript
Vue入门之animate过渡动画效果
2018/04/08 Javascript
VUE脚手架具体使用方法
2019/05/20 Javascript
JavaScript中EventBus实现对象之间通信
2020/10/18 Javascript
[03:40]DOTA2亚洲邀请赛小组赛第二日 赛事回顾
2015/01/31 DOTA
详解Python的Django框架中的templates设置
2015/05/11 Python
pandas修改DataFrame列名的方法
2018/04/08 Python
Pycharm配置远程调试的方法步骤
2018/12/17 Python
基于Python的Post请求数据爬取的方法详解
2019/06/14 Python
Tensorflow 定义变量,函数,数值计算等名字的更新方式
2020/02/10 Python
Python3爬虫中Selenium的用法详解
2020/07/10 Python
UGG雪地靴德国官网:UGG德国
2016/11/19 全球购物
师范生自我鉴定
2014/03/20 职场文书
安全负责人任命书
2014/06/06 职场文书
奥巴马当选演讲稿
2014/09/10 职场文书
教师作风建设剖析材料
2014/10/11 职场文书
老乡聚会通知
2015/04/23 职场文书
关爱留守儿童捐款倡议书
2015/04/27 职场文书
微信小程序结合ThinkPHP5授权登陆后获取手机号
2021/11/23 PHP
Mysql如何实现不存在则插入,存在则更新
2022/03/25 MySQL