palabs/php-enum

类似于 Java 的 PHP 枚举实现,适用于 php 7.4+

0.2.1 2020-04-13 12:59 UTC

This package is auto-updated.

Last update: 2024-09-13 23:43:24 UTC


README

Build Status Latest Stable Version License

好处

  • 类型提示:function someAction(Action $action) {
  • 没有魔法方法或 phpdoc 注释,只有原始枚举值
  • 所有可能值的列表
  • 枚举中的自有字段或方法

安装

composer require palabs/php-enum

创建第一个枚举

use PaLabs\Enum\Enum;

class Action extends Enum
{
    public static Action $VIEW, $EDIT;
}
Action::init();

这就完了!

示例

function someAction(Action $action) {
   switch($action) {
       case Action::$VIEW:
           // some code
       break;
       case Action::$EDIT:
           // another code
       break;
       default:
           // ...
       break;
   }
}

$viewAction = Action::$VIEW;
if($viewAction->equals(ACTION::$EDIT)) {
// ...
}

$allActions = Action::values();

枚举中的自定义字段

use PaLabs\Enum\Enum;

class Planet extends Enum
{
   public static Planet 
       $MERCURY,
       $VENUS,
       $EARTH,
       $MARS,
       $JUPITER,
       $SATURN,
       $URANUS,
       $NEPTUNE;

   private float $mass;   // in kilograms
   private float $radius; // in meters
   
   public function __construct(float $mass, float $radius) {
       $this->mass = $mass;
       $this->radius = $radius;
   }

   private const G = 6.67300E-11;

   public function surfaceGravity(): float {
       return self::G * $this->mass / ($this->radius * $this->radius);
   }
   public function surfaceWeight(float $otherMass): float {
       return $otherMass * $this->surfaceGravity();
   }

}

Planet::$MERCURY = new Planet(3.303e+23, 2.4397e6);
Planet::$VENUS = new Planet(4.869e+24, 6.0518e6);
Planet::$EARTH = new Planet(5.976e+24, 6.37814e6);
Planet::$MARS = new Planet(6.421e+23, 3.3972e6);
Planet::$JUPITER = new Planet(1.9e+27,   7.1492e7);
Planet::$SATURN = new Planet(5.688e+26, 6.0268e7);
Planet::$URANUS = new Planet(8.686e+25, 2.5559e7);
Planet::$NEPTUNE = new Planet(1.024e+26, 2.4746e7);
Planet::init();

$yourEarthWeight = 65.0;
$mass = $yourEarthWeight / Planet::$EARTH->surfaceGravity();
foreach (Planet::values() as $planet) {
   sprintf("Your weight on %s is %f%n", $planet->name(), $planet->surfaceWeight($mass));
}

方法

  • name() 返回当前枚举实例的名称(例如,对于 Action::$VIEW,为 'VIEW')
  • ordinal() 返回枚举实例在所有枚举实例中的序号,从 0 开始。例如,Action::$VIEW 为 0,Action::$EDIT 为 1
  • equals(Enum $other) - 检查枚举实例是否相等

静态方法

  • values() 返回所有枚举实例
  • valueOf(string $name) 返回给定名称的枚举实例,如果未找到枚举实例则抛出异常
  • init() - 初始化枚举(填充枚举实例)。需要在枚举声明后调用