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 相关文章推荐
ajax缓存问题解决途径
Dec 06 PHP
PHP网站安装程序制作的原理、步骤、注意事项和示例代码
Aug 01 PHP
apache mysql php 源码编译使用方法
May 03 PHP
解析php dirname()与__FILE__常量的应用
Jun 24 PHP
PHP 转义使用详解
Jul 15 PHP
php递归法读取目录及文件的方法
Jan 30 PHP
PHP+Javascript实现在线拍照功能实例
Jul 18 PHP
php正则表达式学习笔记
Nov 13 PHP
在WordPress的文章编辑器中设置默认内容的方法
Dec 29 PHP
thinkphp框架page类与bootstrap分页(美化)
Jun 25 PHP
PHP+原生态ajax实现的省市联动功能详解
Aug 15 PHP
PHP+ajax实现上传、删除、修改单张图片及后台处理逻辑操作详解
Feb 12 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
Yii框架关联查询with用法分析
2014/12/02 PHP
smarty学习笔记之常见代码段用法总结
2016/03/19 PHP
Laravel中使用Queue的最基本操作教程
2017/12/27 PHP
JS(jQuery)实现聊天接收到消息语言自动提醒功能详解【提示“您有新的消息请注意查收”】
2019/04/16 PHP
PHP基于进程控制函数实现多线程
2020/12/09 PHP
passwordStrength 基于jquery的密码强度检测代码使用介绍
2011/10/08 Javascript
基于jquery的不规则矩形的排列实现代码
2012/04/16 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
iframe里的页面禁止右键事件的方法
2014/06/10 Javascript
jQuery插件animateSlide制作多点滑动幻灯片
2015/06/11 Javascript
使用微信内嵌H5网页解决JS倒计时失效问题
2017/01/13 Javascript
jQuery EasyUI 为Combo,Combobox添加清除值功能的实例
2017/04/13 jQuery
JS移动端/H5同时选择多张图片上传并使用canvas压缩图片
2017/06/20 Javascript
微信小程序数据存储与取值详解
2018/01/30 Javascript
深入了解JavaScript 防抖和节流
2019/09/12 Javascript
[02:33]2014DOTA2 TI每日综述 LGD涉险晋级DK闯入胜者组
2014/07/14 DOTA
[03:30]完美盛典趣味短片 CSGO2019年度名场面
2019/12/07 DOTA
Python中for循环详解
2014/01/17 Python
深入讨论Python函数的参数的默认值所引发的问题的原因
2015/03/30 Python
win10下python3.5.2和tensorflow安装环境搭建教程
2018/09/19 Python
python去除拼音声调字母,替换为字母的方法
2018/11/28 Python
pandas读取csv文件,分隔符参数sep的实例
2018/12/12 Python
超简单使用Python换脸实例
2019/03/27 Python
Tensorflow中k.gradients()和tf.stop_gradient()用法说明
2020/06/10 Python
scrapy处理python爬虫调度详解
2020/11/23 Python
印尼在线精品店:Berrybenka.com
2016/10/22 全球购物
加拿大最大的体育用品、鞋类和服装零售商:Sport Chek
2018/11/29 全球购物
菲律宾优惠券网站:MetroDeal
2019/04/12 全球购物
阿联酋最好的手机、电子产品和家用电器网上商店:Eros Digital Home
2020/08/09 全球购物
幼教毕业生自我鉴定
2014/01/12 职场文书
环境保护标语
2014/06/20 职场文书
交通事故和解协议书
2015/01/27 职场文书
聘用合同范本
2015/09/21 职场文书
《游戏王:大师决斗》将推出新卡牌包4月4日上线
2022/03/31 其他游戏
Windows Server 2012 R2 磁盘分区教程
2022/04/29 Servers
Java结构型设计模式之组合模式详解
2022/09/23 Java/Android