paillechat/php-enum

PHP 7 的 Enum 实现

2.1 2018-07-10 09:57 UTC

This package is not auto-updated.

Last update: 2024-09-20 17:27:31 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads

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();