您好,欢迎访问一九零五行业门户网

PHP中Enum(枚举)用法实例详解_PHP

本文实例讲述了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 ]] )}
使用示例:
getmessage() . php_eol;}?>
输出结果:
6value not a const in enum month
(2)自定义的enum类库
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 __defaultvar_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程序设计有所帮助。
其它类似信息

推荐信息