paillechat / php-enum
PHP 7 的 Enum 实现
2.1
2018-07-10 09:57 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^7.0
- squizlabs/php_codesniffer: ^2.8
- symfony/phpunit-bridge: ^4.0
This package is not auto-updated.
Last update: 2024-09-20 17:27:31 UTC
README
PHP 7+ 枚举库。
为什么?
为 PHP 库创建完美的枚举
安装
composer require "paillechat/php-enum:^2.0"
使用
通过扩展基本 Enum
并填充常量来声明枚举类。常量值不重要。你可以用任何可以作为通用常量利用的有效负载填充它,但我们建议尽可能将常量保持为 protected
。
<?php use Paillechat\Enum\Enum; /** * These docs are used only to help IDE * * @method static static ONE * @method static static TWO */ class IssueType extends Enum { protected const ONE = 1; protected const TWO = 2; } # Now you can create enum via named static call /** @var Enum $one */ $one = IssueType::ONE(); # Enums keeps strict equality $one1 = IssueType::ONE(); $one2 = IssueType::ONE(); $two = IssueType::TWO(); $one1 === $one2; $one !== $two; # Enums plays well with built-in functions \in_array(IssueType::ONE(), [$one, $two], true); # Enums plays well with signature type checks function moveIssue(IssueType $type) { if ($type === IssueType::ONE()) { throw new \LogicException(); } // .... } # You can convert enum to name and back $name = $one->getName(); $new = IssueType::$name();