PHP模拟枚举类型

 

下面是TEnum源代码,枚举的祖先类。

   1: 
   
   

    
   2: abstract class TEnum {
   3:     /**
   4:      * 枚举元素的数组。
   5:      *
   6:      * @var array
   7:      */
   8:     protected $FValues;
   9:     
  10:     /**
  11:      * 添加元素
  12:      *
  13:      * @param integer $Element
  14:      */
  15:     protected function Add($Element) {
  16:         $this->FValues[$Element] = $Element;
  17:     }
  18:     
  19:     /**
  20:      * 进行初始化,定义枚举范围。
  21:      *
  22:      */
  23:     abstract protected function DoInit();
  24:     
  25:     /**
  26:      * 选择枚举元素。
  27:      *
  28:      * @param integer $Element 元素名称
  29:      * @return integer 元素值
  30:      */
  31:     public static function Get($Element) {
  32:         if (array_key_exists($Element, $this->FValues)) {
  33:             return ($this->FValues[$Element]);
  34:         }
  35:         else {
  36:             throw new ENotInEnum("{$Element} is not in enum {__CLASS__}"); //ENotInEnum是一个自定义的异常类。
  37:         }
  38:     }
  39:     
  40:     function __construct($Element) {
  41:         $this->DoInit();
  42:         $this->Get($Element);
  43:     }
  44: }
  45: ?>

 

然后,定义一个自定义的枚举类型。

   1: /**
   2:  * 一个自定义的枚举。
   3:  *
   4:  */
   5: final class TMyCustomEnum extends TEnum {
   6:     const ItemA = 0;
   7:     const ItemB = 1;
   8:     const ItemC = 2;
   9:     const ItemD = 3;
  10:     //定义枚举元素
  11:     
  12:     /**
  13:      * 枚举初始化。
  14:      * @see TEnum::DoInit()
  15:      *
  16:      */
  17:     protected function DoInit() {
  18:         self::Add(self::ItemA);
  19:         self::Add(self::ItemB);
  20:         self::Add(self::ItemC);
  21:         self::Add(self::ItemD);
  22:         //添加枚举元素
  23:     }
  24: }
  25: */

最后是使用它:

   1: $MyEnumValue=new TMyCustomEnum(TMyCustomEnum::ItemA);
   2: //这时,$MyEnumValue就是等于ItemA。

 

不过使用这个方法,还有许多的缺点……还有待改进。

Technorati 标签: , ,
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值