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 操作文件的一些FAQ总结
Feb 12 PHP
PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
Jul 17 PHP
PHP删除HTMl标签的实现代码
Jun 30 PHP
Fatal error: session_start(): Failed to initialize storage module: files问题解决方法
May 04 PHP
php版本的cron定时任务执行器使用实例
Aug 19 PHP
PHP使用get_headers函数判断远程文件是否存在的方法
Nov 28 PHP
10个简化PHP开发的工具
Dec 25 PHP
symfony2.4的twig中date用法分析
Mar 18 PHP
PHP+AjaxForm异步带进度条上传文件实例代码
Aug 14 PHP
PHP基于SPL实现的迭代器模式示例
Apr 22 PHP
在Laravel中使用GuzzleHttp调用第三方服务的API接口代码
Oct 15 PHP
laravel 出现command not found问题的解决方案
Oct 23 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执行速率优化技巧小结
2008/03/15 PHP
PHP中使用循环实现的金字塔图形
2014/11/08 PHP
Yii控制器中操作视图js的方法
2016/07/04 PHP
用JS操作FRAME中的IFRAME及其内容的实现代码
2008/07/26 Javascript
Javascript 日期对象Date扩展方法
2009/05/30 Javascript
javascript 单例/单体模式(Singleton)
2011/04/07 Javascript
JavaScript操作选择对象的简单实例
2016/05/16 Javascript
两种JavaScript的AES加密方式(可与Java相互加解密)
2016/08/02 Javascript
js实现表单及时验证功能 用户信息立即验证
2016/09/13 Javascript
微信小程序 icon组件详细及实例代码
2016/10/25 Javascript
微信小程序 动态绑定事件并实现事件修改样式
2017/04/13 Javascript
详解Vue 动态添加模板的几种方法
2017/04/25 Javascript
详解JavaScript按概率随机生成事件
2017/08/02 Javascript
Node.js调用fs.renameSync报错(Error: EXDEV, cross-device link not permitted)
2017/12/27 Javascript
vue fetch中的.then()的正确使用方法
2020/04/17 Javascript
彻底搞懂并解决vue-cli4中图片显示的问题实现
2020/08/31 Javascript
基于javascript实现移动端轮播图效果
2020/12/21 Javascript
[02:30]辉夜杯主赛事第二日胜者组半决赛 CDEC.Y赛后采访
2015/12/26 DOTA
python中执行shell命令的几个方法小结
2014/09/18 Python
全面理解Python中self的用法
2016/06/04 Python
python函数的5种参数详解
2017/02/24 Python
Python实现对一个函数应用多个装饰器的方法示例
2018/02/09 Python
详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决
2019/08/27 Python
浅析PEP570新语法: 只接受位置参数
2019/10/15 Python
python被修饰的函数消失问题解决(基于wraps函数)
2019/11/04 Python
flask框架蓝图和子域名配置详解
2020/01/25 Python
详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库
2021/01/24 Python
利用CSS3制作简单的3d半透明立方体图片展示
2017/03/25 HTML / CSS
详解如何在css3打包后自动追加前缀插件:autoprefixer
2018/12/18 HTML / CSS
马来西亚领先的在线礼品店:Giftr
2018/08/23 全球购物
总经理任命书
2014/03/29 职场文书
人事局接收函
2015/01/30 职场文书
2015年上半年信访工作总结
2015/03/30 职场文书
辩论赛主持人开场白
2015/05/29 职场文书
Java基础之线程锁相关知识总结
2021/06/30 Java/Android
Windows Server 修改远程桌面端口的实现
2022/06/25 Servers