PHP 枚举实现

1.6.0 2017-01-19 16:21 UTC

This package is not auto-updated.

Last update: 2024-09-15 00:54:36 UTC


README

Build Status Latest Stable Version Total Downloads

为什么使用?

首先,主要是,PHP 中的 SplEnum 没有集成,您需要单独安装。

使用枚举而不是类常量有以下优点

  • 您可以进行类型提示:function setAction(Action $action) {
  • 您可以丰富枚举的方法(例如 formatparse 等)
  • 您可以扩展枚举以添加新值(使您的枚举 final 以防止扩展)
  • 您可以获取所有可能值的列表(见下文)

这个 Enum 类不是用来替换类常量的,而只是在有意义的时候使用。

安装

composer require myclabs/php-enum

声明

use MyCLabs\Enum\Enum;

/**
 * Action enum
 */
class Action extends Enum
{
    const VIEW = 'view';
    const EDIT = 'edit';
}

使用

$action = new Action(Action::VIEW);

// or
$action = Action::VIEW();

如您所见,静态方法会自动实现,以便快速访问枚举值。

与使用类常量相比的一个优势是可以对枚举值进行类型提示

function setAction(Action $action) {
    // ...
}

文档

  • __construct() 构造函数检查值是否存在于枚举中
  • __toString() 您可以使用 echo $myValue,它将显示枚举值(常量的值)
  • getValue() 返回枚举的当前值
  • getKey() 返回当前值在 Enum 上的键
  • equals() 检查枚举实例是否相等(如果枚举值相等,则返回 true,否则返回 false

静态方法

  • toArray() 方法返回所有可能值的数组(键为常量名,值为常量值)
  • keys() 返回 Enum 类中所有常量的名称(键)
  • values() 返回所有 Enum 常量的 Enum 类实例(键为常量名,值为 Enum 实例)
  • isValid() 检查测试的值是否在枚举集中有效
  • isValidKey() 检查测试的键是否在枚举集中有效
  • search() 返回搜索值的键

静态方法

class Action extends Enum
{
    const VIEW = 'view';
    const EDIT = 'edit';
}

// Static method:
$action = Action::VIEW();
$action = Action::EDIT();

使用 __callStatic() 实现了静态方法辅助器。

如果您关注 IDE 自动完成,您可以选择自己实现静态方法

class Action extends Enum
{
    const VIEW = 'view';

    /**
     * @return Action
     */
    public static function VIEW() {
        return new Action(self::VIEW);
    }
}

或者您可以使用 phpdoc(例如,在 PhpStorm 中支持此功能)

/**
 * @method static Action VIEW()
 * @method static Action EDIT()
 */
class Action extends Enum
{
    const VIEW = 'view';
    const EDIT = 'edit';
}