本文实例讲述了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 ]] )

}

使用示例:

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类库

/**

* 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

* @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中Enum(枚举)用法实例详解相关推荐

  1. python编程字典100例_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  2. python 字典定义日志用法_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  3. JavaScript中window.open用法实例详解

    本文较为详细的分析了JavaScript中window.open用法.分享给大家供大家参考.具体如下: 复制代码 代码如下: <script LANGUAGE="javascript& ...

  4. python argparse模块详解_python中argparse模块用法实例详解

    本文实例讲述了python中argparse模块用法.分享给大家供大家参考.具体分析如下: 平常在写命令行工具的时候,经常会带参数,所以用python中的argparse来实现. # -*- codi ...

  5. C#中Socket通信用法实例详解

    本文实例讲述了C#中Socket通信用法.分享给大家供大家参考.具体如下: 一.UDP方式: 服务器端代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 ...

  6. python print函数用法_Python3.2中Print函数用法实例详解

    本文实例讲述了Python3.2中Print函数用法.分享给大家供大家参考.具体分析如下: 1. 输出字符串 >>> strHello = 'Hello World' >> ...

  7. python类初始化导入库_Python中optparser库用法实例详解

    本文研究的主要是Python中optparser库的相关内容,具体如下. 一直以来对optparser不是特别的理解,今天就狠下心,静下心研究了一下这个库.当然了,不敢说理解的很到位,但是足以应付正常 ...

  8. [转载] python里字典的用法_python中字典(Dictionary)用法实例详解

    参考链接: Python字典dictionary copy方法 本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映 ...

  9. java中用法实例_java中Calendar类用法实例详解

    本文实例讲述了java中Calendar类用法.分享给大家供大家参考,具体如下: java中的Calendar在开发中经常被忽略,这篇博客总结一下这个类,对后面项目中使用时期的时候有帮助. Calen ...

  10. PHP中spl_autoload_register()函数用法实例详解

    在了解这个函数之前先来看另一个函数:__autoload. 一.__autoload 这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数.看下面例子: printit.c ...

最新文章

  1. Java I/O 操作及优化建议
  2. 02.uri-search
  3. Loadrunner学习笔记(四)
  4. BZOJ3930-莫比乌斯反演+杜教筛
  5. RMAN备份与恢复(三)--备份相关概念
  6. MyBatis 简介
  7. linux shell 数字雨,cmd命令如何实现数字雨的效果
  8. Unity3d开发环境如何
  9. 乡村振兴专题:农村面板数据3.0
  10. 化学专业与计算机的联系PPT,计算机在化学中的应用ppt
  11. cdr怎么做文字路径_CorelDRAW如何制作环绕圆形的路径文字
  12. 关于小米驱动程序的问题
  13. 一个SQL tvp+.net的例子
  14. 淘宝商城发公告释疑2012新规 称调整绝不是涨价
  15. 生活中软件易用性的例子_多用“举出例子”“比如说”,来进行生活中的语言交流...
  16. 《赵成的运维体系管理课》学习笔记(3)——云计算时代的运维实践
  17. 人活着的意义__2014思想篇
  18. python launcher卸载后蓝屏_安装win7x64、x86总提示文件出错或安装大型软件出错或0x0000001a、0x0000003b蓝屏...
  19. 刷脸支付帮助商户吸引和服务消费者
  20. python 封闭图形面积_python opencv填充未完全闭合的等高线

热门文章

  1. ajax发送post请求_按键精灵安卓版发送post和get请求
  2. IIS6下配置fastcgi的php的教程
  3. 产品定义到产品推广的思路
  4. Struts2学习第七课 ActionSupport
  5. Omi框架学习之旅 - 生命周期 及原理说明
  6. Visual Studio插件
  7. 【MDCC技术大咖秀】Android内存优化之OOM
  8. 15、Cocos2dx 3.0游戏开发找小三之Sprite:每一个精灵都是上辈子折翼的天使
  9. flash与IPhone
  10. 拖动无标题栏的窗体,需要处理的三个事件