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 相关文章推荐
CodeIgniter php mvc框架 中国网站
May 26 PHP
PHP取进制余数函数代码
Jan 19 PHP
Yii框架表单模型和验证用法
May 20 PHP
PHP isset()与empty()的使用区别详解
Feb 10 PHP
php实现留言板功能
Mar 05 PHP
yii2使用gridView实现下拉列表筛选数据
Apr 10 PHP
PHP使用数组实现矩阵数学运算的方法示例
May 29 PHP
PHP大文件分割上传 PHP分片上传
Aug 28 PHP
CentOS7.0下安装PHP5.6.30服务的教程详解
Sep 29 PHP
thinkphp5框架API token身份验证功能示例
May 21 PHP
php项目中类的自动加载实例讲解
Sep 12 PHP
php反序列化长度变化尾部字符串逃逸(0CTF-2016-piapiapia)
Feb 15 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
ajax 的post方法实例(带循环)
2011/07/04 PHP
codeigniter实现get分页的方法
2015/07/10 PHP
thinkPHP5.0框架引入Traits功能实例分析
2017/03/18 PHP
PHP实现求两个字符串最长公共子串的方法示例
2017/11/17 PHP
解决Laravel5.x的php artisan migrate数据库迁移创建操作报错SQLSTATE[42000]
2020/04/06 PHP
自动更新作用
2006/10/08 Javascript
javascript 面向对象全新理练之原型继承
2009/12/03 Javascript
javascript下判断一个元素是否存在的代码
2010/03/05 Javascript
JavaScript字符串对象charAt方法入门实例(用于取得指定位置的字符)
2014/10/17 Javascript
javascript模拟map输出与去除重复项的方法
2015/02/09 Javascript
多种js图片预加载实现方式分享
2016/02/19 Javascript
Jquery操作cookie记住用户名
2016/03/29 Javascript
Bootstrap编写导航栏和登陆框
2016/05/30 Javascript
Google 地图事件实例讲解
2016/08/06 Javascript
jquery实现网站列表切换效果的2种方法
2016/08/12 Javascript
微信小程序+腾讯地图开发实现路径规划绘制
2019/05/22 Javascript
jQuery实现开关灯效果
2020/08/02 jQuery
Python变量和字符串详解
2017/04/29 Python
Python实现的直接插入排序算法示例
2018/04/29 Python
python利用Tesseract识别验证码的方法示例
2019/01/21 Python
Python 实现Image和Ndarray互相转换
2020/02/19 Python
Python count函数使用方法实例解析
2020/03/23 Python
详解pycharm连接远程linux服务器的虚拟环境的方法
2020/11/13 Python
pandas针对excel处理的实现
2021/01/15 Python
python 求两个向量的顺时针夹角操作
2021/03/04 Python
canvas像素点操作之视频绿幕抠图
2018/09/11 HTML / CSS
吉列剃须刀美国官网:Gillette美国
2018/07/13 全球购物
班级道德讲堂实施方案
2014/02/24 职场文书
垃圾桶标语
2014/06/24 职场文书
幼儿园大班教师个人工作总结
2015/02/05 职场文书
考博导师推荐信范文
2015/03/27 职场文书
2015年领导班子工作总结
2015/05/23 职场文书
导游词之蜀山胜景瓦屋山
2019/11/29 职场文书
MySql 8.0及对应驱动包匹配的注意点说明
2021/06/23 MySQL
python实现简易自习室座位预约系统
2021/06/30 Python
安装Ruby和 Rails的详细步骤
2022/04/19 Ruby