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 相关文章推荐
推荐一篇入门级的Class文章
Mar 19 PHP
php重定向的三种方法分享
Feb 22 PHP
php创建sprite
Feb 11 PHP
Windows下的PHP安装pear教程
Oct 24 PHP
PHP中使用break跳出多重循环代码实例
Jan 21 PHP
PHP rsa加密解密使用方法
Apr 27 PHP
PHP伪造来源HTTP_REFERER的方法实例详解
Jul 06 PHP
windows8.1下Apache+Php+MySQL配置步骤
Oct 30 PHP
php简单统计中文个数的方法
Sep 30 PHP
PHP实现模拟http请求的方法分析
Dec 20 PHP
Laravel实现通过blade模板引擎渲染视图
Oct 25 PHP
让whoops帮我们告别ThinkPHP6的异常页面
Mar 02 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 has encountered an Access Violation 错误的解决方法
2010/01/17 PHP
PHP 输出URL的快捷方式示例代码
2013/09/22 PHP
PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)
2016/12/14 PHP
PHP实现普通hash分布式算法简单示例
2018/08/06 PHP
jQuery编写widget的一些技巧分享
2010/10/28 Javascript
Javascript四舍五入Math.round()与Math.pow()使用介绍
2013/12/27 Javascript
jquery动态改变form属性提交表单
2014/06/03 Javascript
详谈javascript中的cookie
2015/06/03 Javascript
Spring MVC中Ajax实现二级联动的简单实例
2016/07/06 Javascript
jQuery EasyUI中的日期控件DateBox修改方法
2016/11/09 Javascript
JS中如何实现复选框全选功能
2016/12/19 Javascript
javascript 数据存储的常用函数总结
2017/06/01 Javascript
node.js + socket.io 实现点对点随机匹配聊天
2017/06/30 Javascript
Nodejs中crypto模块的安全知识讲解
2018/01/03 NodeJs
理解Koa2中的async&amp;await的用法
2018/02/05 Javascript
webpack热模块替换(HMR)/热更新的方法
2018/04/05 Javascript
详解Vue webapp项目通过HBulider打包原生APP
2018/06/29 Javascript
微信小程序将字符串生成二维码图片的操作方法
2018/07/17 Javascript
JavaScript基础之静态方法和实例方法分析
2018/12/26 Javascript
vue项目中引入vue-datepicker插件的详解
2019/05/14 Javascript
微信小程序swiper禁止用户手动滑动代码实例
2019/08/23 Javascript
element el-tree组件的动态加载、新增、更新节点的实现
2020/02/27 Javascript
如何在VUE中使用vue-awesome-swiper
2021/01/04 Vue.js
Python迭代和迭代器详解
2016/11/10 Python
python3+PyQt5使用数据库窗口视图
2018/04/24 Python
Python根据指定文件生成XML的方法
2020/06/29 Python
Python如何定义有默认参数的函数
2020/08/10 Python
python实现马丁策略的实例详解
2021/01/15 Python
REN Clean Skincare官网:英国本土有机护肤品牌
2019/02/23 全球购物
超级搞笑检讨书
2014/01/15 职场文书
安全生产承诺书范文
2014/05/22 职场文书
大学毕业生管理学求职信
2014/09/01 职场文书
少年犯观后感
2015/06/11 职场文书
2015年中秋晚会主持稿
2015/07/30 职场文书
如何书写授权委托书?
2019/06/25 职场文书
python删除csv文件的行列
2021/04/06 Python