morilog / php-enum
本包的最新版本(1.0.1)没有提供许可信息。
一个用于在PHP编程语言中轻松处理枚举的库
1.0.1
2019-08-14 16:53 UTC
Requires
- php: >=7.1.0
- beberlei/assert: ^3.2
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is auto-updated.
Last update: 2024-09-15 04:47:28 UTC
README
PHP-ENUM
PHP编程语言中没有内置的ENUM
。顺便说一句,每个程序员都可能需要这个功能。
在这个库中,我提供了简单易用的枚举处理方法。
安装
运行以下命令
composer require morilog/php-enum
用法
编写新的枚举
创建一个扩展\Morilog\PhpEnum\Enum
类的类
常量键必须是全部大写,单词之间用
_
(下划线)分隔
常量值可以是所有标量值,例如
string
、integer
、boolean
等。
<?php use Morilog\PhpEnum\Enum; final class CommentStatus extends Enum { const APPROVED = 1; const REJECTED = 2; const SOMETHING_ELSE = 3; }
创建枚举实例
通过类构造函数
<?php $status = new CommentStatus(1); $status->key(); // APPROVED $status->value(); // 1 $status->isApproved(); // true $status->isRejected(); // false
通过camelCase
常量名称
<?php $status = CommentStatus::rejected(); $status->key(); // REJECTED $status->value(); // 2 $status->isApproved(); // false $status->isRejected(); // true $other = CommentStatus::somethingElse(); $other->key(); // SOMETHING_ELSE $other->value(); // 3 $other->isApproved(); // false $other->isRejected(); // false $other->isSomethingElse(); // true
通过fromKey()
方法
<?php $status = CommentStatus::fromKey('APPROVED');
通过fromValue()
方法
<?php $status = CommentStatus::fromValue(1);
静态方法
<?php CommentStatus::keys(); // [APPROVED, REJECTED, SOMETHING_ELSE] CommentStatus::values(); // [1, 2, 3] CommentStatus::toArray(); // [APPROVED => 1, REJECTED => 2, SOMETHING_ELSE => 3]
比较枚举
<?php $first = CommentStatus::approved(); $second = CommentStatus::rejected(); $third = CommentStatus::approved(); $first->equalsTo($second); // false $first->equalsTo($third); // true