neutronstars / enum
为早期版本添加了一个尽可能接近PHP 8.1的枚举系统。
1.4.0
2021-07-08 20:26 UTC
Requires
- php: ^7.1 | ^8.0
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^6.0 | ^7.0 | ^8.0 | ^9.0
This package is auto-updated.
Last update: 2024-09-09 23:11:42 UTC
README
安装
仅适用于没有Doctrine和Symfony的Enum PHP
composer require neutronstars/enum
对于Doctrine
composer require neutronstars/doctrine-enum-php-type
对于Symfony
composer require neutronstars/symfony-normalizer-enum-php
文档:https://github.com/Neutron-Pro/symfony-normalizer-enum-php
对于Symfony和Doctrine
composer require neutronstars/doctrine-enum-php-type
composer require neutronstars/symfony-normalizer-enum-php
如何创建Enum类
方法1
/** * @method static self ONE() * @method static self TWO() * @method static self THREE() */ class MyEnum extends \NeutronStars\Enum\Enum { public const ONE = null; public const TWO = null; public const THREE = null; }
这个枚举不需要构造函数。我们只是创建了一个没有任何值(除了其名称)的常量列表。
方法2
/** * @method static self ONE() * @method static self TWO() * @method static self THREE() */ class MyStringEnum extends \NeutronStars\Enum\Enum { public const ONE = 'One'; public const TWO = 'Two'; public const THREE = 'Three'; }
/** * @method static self ONE() * @method static self TWO() * @method static self THREE() */ class MyIntEnum extends \NeutronStars\Enum\Enum { public const ONE = 1; public const TWO = 2; public const THREE = 3; }
使用Enum类
获取枚举实例
$two = MyStringEnum::TWO(); echo $two; // return TWO echo $two->key; // return TWO echo $two->value; // return Two
从字符串获取枚举实例
$three = MyStringEnum::from('THREE'); echo $three; // THREE echo $three->key; // return THREE echo $three->value; // return Three
比较枚举实例
$value = MyStringEnum::tryFrom($_GET['number']); if ($value === MyStringEnum::ONE()) { echo 'The number is ONE !'; }
结果
if $_GET['number] is ONE or One or 1 then 'The number is ONE !'
else nothing.
from 和 tryFrom 的区别。
如果你使用 "tryFrom" 并且参数值未找到,该方法返回null。
如果你使用 "from" 并且参数值未找到,将抛出一个 ValueError 类型的错误。
检索枚举的所有键。
$cases = MyIntEnum::cases();
结果
[
MyIntEnum::ONE(),
MyIntEnum::TWO(),
MyIntEnum::THREE()
]
foreach (MyIntEnum::cases() as $case) { echo '- ' . $case->value; }
结果
- 1
- 2
- 3
序列化和反序列化
你可以使用PHP的serialize函数序列化枚举。
$serialized = serialize(MyEnum::THREE());
但对于反序列化,会有一个小差异,你必须使用 from 或 tryFrom 方法
$deserialized = MyEnum::from(unserialize($deserialized)); // $deserialized = MyEnum::THREE()