phpgears / enum
PHP 的枚举
0.3
2020-03-07 11:35 UTC
Requires
- php: ^7.1
- phpgears/immutability: ~0.2.2
Requires (Dev)
- brainmaestro/composer-git-hooks: ^2.8
- friendsofphp/php-cs-fixer: ^2.16
- infection/infection: ^0.13|^0.15
- overtrue/phplint: ^1.2
- phpmd/phpmd: ^2.8
- phpstan/extension-installer: ^1.0.3
- phpstan/phpstan: ^0.12
- phpstan/phpstan-deprecation-rules: ^0.12
- phpstan/phpstan-strict-rules: ^0.12
- phpunit/phpunit: ^7.5|^8.0
- povils/phpmnd: ^2.1
- roave/security-advisories: dev-master
- sebastian/phpcpd: ^4.0
- squizlabs/php_codesniffer: ^3.5
- thecodingmachine/phpstan-strict-rules: ^0.12
README
枚举
不可变枚举对象用于 PHP
其他语言有枚举的概念,虽然 PHP 有枚举的扩展,但默认并不提供或普及
实现枚举类并不困难,但它应该包含值验证并且是不可变的,因此其值不能被更改
安装
Composer
composer require phpgears/enum
使用
需要 composer 自动加载文件
require './vendor/autoload.php';
通过扩展 Gears\Enum\AbstractEnum
,您可以轻松地创建枚举类
use Gears\Enum\AbstractEnum; /** * @method static self DAILY() * @method static self WEEKLY() * @method static self BIWEEKLY() * @method static self MONTHLY() * @method static self YEARLY() */ final class DatePeriod extends AbstractEnum { public const DAILY = 'daily'; public const WEEKLY = 'weekly'; public const BIWEEKLY = 'biweekly'; public const MONTHLY = 'monthly'; public const YEARLY = 'yearly'; } $period = new DatePeriod('daily'); $period->getValue() === DatePeriod::DAILY; // true $period->isEqualTo(DatePeriod::DAILY()); // true $period->isAnyOf([DatePeriod::DAILY(), DatePeriod::WEEKLY()]); // true $period->getValue() === DatePeriod::YEARLY; // false $period->isEqualTo(DatePeriod::MONTHLY()); // false $period->isAnyOf([DatePeriod::MONTHLY(), DatePeriod::YEARLY()]); // false $period->getValue(); // daily $newPeriod = new DatePeriod($period); $newPeriod->getValue() === DatePeriod::DAILY; // true $newPeriod->getValue() === $period->getValue(); // true $newPeriod->isEqualTo($period); // true $newPeriod->getValue(); // daily
枚举 必须 始终定义为最终类
建议在类的文档块上添加 @method
注解引用,以便您的编辑器能够帮助您完成自动补全
贡献
发现了一个错误或有功能请求? 请打开一个新的问题。在提交之前请查看现有的问题。
查看文件 CONTRIBUTING.md
许可证
请参阅源代码中包含的 LICENSE 文件以获取许可证条款的副本。