加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-12 21:12:08 所属栏目:PHP教程 来源:网络整理
导读:本篇章节讲解PHP中Enum(枚举)用法。供大家参考研究具体如下: PHP其实有Enum类库的,需要安装perl扩展,所以不是php的标准扩展,因此代码的实现需要运行的php环境支持。 (1)扩展类库SplEnum类。该类的摘要如下: 使用示例: getMessage() . PHP_

本篇章节讲解PHP中Enum(枚举)用法。分享给大家供大家参考,具体如下:

PHP其实有Enum类库的,需要安装perl扩展,所以不是php的标准扩展,因此代码的实现需要运行的php环境支持。

(1)扩展类库SplEnum类。该类的摘要如下:

使用示例:

getMessage() . PHP_EOL; } ?>

输出结果:

(2)自定义的Enum类库

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); } }

使用示例如下:

getMessage()); }

输出结果如下:

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程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读