如何统一管理的 PHP Enum?-PHP问题

资源魔 33 0

装置

composer require fangx/php-enum

创立

应用 ./vendor/bin/enum 饬令创立一个枚举类.

./vendor/bin/enum FooEnum --enum="1=foo" --enum="b=bar" --path=Enums

该饬令默许正在 以后目次的 Enums 目次下创立一个 FooEnum.php 文件. 文件内容以下:

<?phpnamespace Enums;use Fangx\Enum\AbstractEnum;class FooEnum extends AbstractEnum{
    const FOO = "f", __FOO = "foo";
    const BAR = "b", __BAR = "bar";}

应用

枚举类默许承继 \Fangx\Enum\AbstractEnum. 能够动态挪用如下办法:

  • toArray(Format $format = null, Filter $filter = null)
  • toJson(Format $format = null, Filter $filter = null)
  • desc($key, $default = 'Undefined')

猎取一切的枚举值

<?phpclass FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = 'f', __FOO = 'foo';
    const BAR = 'b', __BAR = 'bar';}/**
 * ['f' => 'foo', 'b' => 'bar']
 */FooEnum::toArray();

猎取枚举值的形容信息

<?phpclass FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = 'f', __FOO = 'foo';
    const BAR = 'b', __BAR = 'bar';}/**
 * "foo"
 */FooEnum::desc('f');/**
 * "bar"
 */FooEnum::desc(FooEnum::BAR);

应用格局来束缚前往值

<?phpclass FooFormat implements \Fangx\Enum\Contracts\Format{
    public function parse(\Fangx\Enum\Contracts\Definition $definition): array
    {
        return [['key' => $definition->getKey() , 'value' => $definition->getValue()]];
    }}class FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = 'f', __FOO = 'foo';
    const BAR = 'b', __BAR = 'bar';}/**
 * [['key' => 'f', 'value' => 'foo'], ['key' => 'b', 'value' => 'bar'],]
 */$format = new FooFormat();FooEnum::toArray($format);

经过规定来过去过滤枚举值.

class FooFilter implements \Fangx\Enum\Contracts\Filter{
    public function __invoke(\Fangx\Enum\Contracts\Definition $definition)
    {
        return $definition->getKey() === 'f';
    }}/**
 * ['f' => 'foo']
 */$filter = new FooFilter();FooEnum::toArray(null, $filter);

应用自界说的荟萃来作为一切的枚举类型, 其余应用办法与 FooEnum 分歧.

<?phpclass BarEnum extends \Fangx\Enum\AbstractEnum{
    public function all()
    {
        return [
            new \Fangx\Enum\Definition('f', 'foo'),
            new \Fangx\Enum\Definition('b', 'bar'),
        ];
    }}

保举教程:《PHP》

以上就是若何对立治理的 PHP Enum?的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 php故障解决 php使用问题 enum

抱歉,评论功能暂时关闭!