转载请保留原文地址:http://www.cnblogs.com/zsxfbj/p/php_enum.html

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

摘自http://www.php4every1.com/scripts/php-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&gt
* @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的Enum(枚举)的实现的更多相关文章

  1. c# (ENUM)枚举组合类型的谷歌序列化Protobuf

    c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...

  2. C#将Enum枚举映射到文本字符串

    介绍 当将以前的C代码移植到C#中时,我快发疯了,因为有很多的数组需要将常量映射到字符串.当我在寻找一个C#的方法来完成的时候,我发现了一个自定义属性和映射的方法. 如何使用代码? 对每一个enum枚 ...

  3. MVC3不能正确识别JSON中的Enum枚举值

    一.背景 在MVC3项目里,如果Action的参数中有Enum枚举作为对象属性的话,使用POST方法提交过来的JSON数据中的枚举值却无法正确被识别对应的枚举值. 二.Demo演示 为了说明问题,我使 ...

  4. 161208、Java enum 枚举还可以这么用

    在大部分编程语言中,枚举类型都会是一种常用而又必不可少的数据类型,Java中当然也不会例外.然而,Java中的Enum枚举类型却有着许多你意想不到的用法,下面让我们一起来看看. 先来看一段代码示例: ...

  5. Python中模拟enum枚举类型的5种方法分享

    这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下   以下几种方法来模拟enum:(感觉方法一简单实用) 复制代码代码如下: # way1 ...

  6. java之enum枚举(2015年05月28日)

    背景: 今天启动了一个新的项目,由于要从之前的旧项目中拿过来一些代码,所以就看了下公司之前项目代码,发现有定义的常量类,也有枚举类,然后就在想着两者的功能差不多,那他们之间到底有什么区别呢,所以就决定 ...

  7. 1.0 基础、标示符、常量、数据类型(enum 枚举,struct 结构体)、操作符、循环、数组

    一.程序 现实生活中,程序是指完成某些事务的一种既定方法和过程,可以把程序看成是一系列动作执行过程的描述. 在计算机世界,程序是指令,即为了让计算机执行某些操作或解决某个问题而编写的一系列有序指令的集 ...

  8. Enum枚举类|注解Annotation

    Enum枚举类 ①枚举类和普通类的差别: 使用 enum 定义的枚举类默认继承了 java.lang.Enum 类 枚举类的构造器仅仅能使用 private 訪问控制符 枚举类的全部实例必须在枚举类中 ...

  9. 中秋佳节--理解Enum枚举

    一.Enum枚举的作用 1.使用枚举可以限定取值范围,枚举中定义的每个常量都可以理解为对象: Eg: Public enum Color{ RED, GREEN,BULE; } 说明:RED实际上就表 ...

  10. 获取Enum枚举值描述的几法方法

    原文:获取Enum枚举值描述的几法方法 1.定义枚举时直接用中文 由于VS对中文支持的很不错,所以很多程序员都采用了此方案. 缺点:1.不适合多语言 2.感觉不太完美,毕竟大部分程序员大部分代码都使用 ...

随机推荐

  1. 2017.11.13 python+ Jlink+EFM32 批量烧录

    1 Add whl files to Python a. install the  environment variable of path b . useing the CMD command  : ...

  2. PostgreSQL日志配置记录

    日志审计  审计是值记录用户的登陆退出以及登陆后在数据库里的行为操作,可以根据安全等级不一样设置不一样级别的审计, 此处涉及的参数文件有: logging_collector      --是否开启日 ...

  3. Scikit-Learn:开源的机器学习Python模块(转载)

    摘要: scikit-learn是一个用于机器学习的Python模块,其具有操作简单.效率高.无访问限制.BSD开源协议等等特征,在机器学习这一块是比较受欢迎的. scikit-learn是一个用于机 ...

  4. 完全卸载session 所需要的函数

    session_unset()  删除内存当中的session数据:必须放在session_destroy的前边.因为应用session_destory后session_id();就会消失. 删除se ...

  5. codevs4189字典

    沙茶 题目大意:求某一个字符串前缀有没有在n个字符串前缀里出现过 题解:Trie树 查询前缀有没有出现 代码: //codevs4189 #include<iostream> #inclu ...

  6. 【LeetCode】汇总

    此贴为汇总贴 673. Number of Longest Increasing Subsequence 075. Sort Colors 009. Palindrome Number 008. St ...

  7. idea操作

    archetypeCatalog  internal 1字体: 2编码 http://blog.csdn.net/frankcheng5143/article/details/50779149 3部署 ...

  8. 如何注册java程序为windows服务

    如何注册java 程序为windows 服务 最近想找个软件来控制电脑的关机时间,在网上找了几个,都是可视化界面的可以设置具体的关机时间的软件.由于我想编写的关机程序是运行在别人机器上,只能让该机器在 ...

  9. Linux cc与gcc

    三个源文件:main.c sum.c show.c /* main.c */ extern int sum(int m, int n); extern void show(int data); int ...

  10. linux 查看系统信息和安装哪些软件的命令

    https://www.cnblogs.com/wangkongming/p/4531341.html 查看系统磁盘硬盘占用率 https://blog.csdn.net/aaashen/articl ...