PHP code example of jiannei / laravel-enum

1. Go to this page and download the library: Download jiannei/laravel-enum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jiannei / laravel-enum example snippets




namespace Jiannei\Enum\Laravel\Tests\Enums;

use Jiannei\Enum\Laravel\Support\Traits\EnumEnhance;

enum UserType: int
{
    use EnumEnhance;

    case ADMINISTRATOR = 0;
    case MODERATOR = 1;
    case SUBSCRIBER = 2;
}

// 获取枚举的值
UserType::ADMINISTRATOR->value;// 0

// 获取所有已定义枚举的名称
$names = UserType::names();// ['ADMINISTRATOR', 'MODERATOR', 'SUBSCRIBER']

// 获取所有已定义枚举的值
$values = UserType::values();// [0, 1, 2]

// 检查定义的枚举中是否包含某个「枚举值」
UserType::hasValue(1);// true
UserType::hasValue(-1);// false

// 检查定义的枚举中是否包含某个「枚举名称」 

UserType::hasName('MODERATOR');// true
UserType::hasName('ADMIN');// false

UserType::fromValue(0) // 通过 value 实例化

UserType::fromName('ADMINISTRATOR') // 通过 name 实例化

UserType::guess(2) // 通过 name/value 猜测

$array = UserType::toArray();

$array = UserType::toSelectArray();// 支持多语言配置

/*
[
    0 => '管理员',
    1 => '监督员',
    2 => '订阅用户',
]
*/