定制 fabiomez/php-enum 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fabiomez/php-enum

Composer 安装命令:

composer require fabiomez/php-enum

包简介

A simple Enum PHP project.

README 文档

README

A simple Enum PHP project.

Why?

Despite when I wrote this little project PHP8 already exists with its own native Enum. I decided to because I had some free time and some projects still using lower PHP versions. Then I decided to write this with all features that I missed in other PHP Enum libraries.

My version of Enum ensure that all instances of the same class constant will always be the same instance. So, does not matter how many times we try to retrieve the enum instance, it will always have the same memory address.

How to install

Require via composer

composer require Fabiomez/php-enum

Or add to your composer.json require session

{
...
  "require": {
    ...
    "Fabiomez/php-enum": "1.0.0"
    ...
  },
...
}

How to use

Declaring

First declare a class that extents from fabiome\Enum\Enum

use Fabiomez\Enum\Enum;

/**
 * @method static self OK
 * @method static self BAD_REQUEST
 */
class HttpCode extends Enum
{
    const OK = 200;
    const BAD_REQUEST = 400;
}
  • DocBlocks is just for IDE auto complete

Retrieving

There are three ways to retrieve Enum instance

Using from static method

$httpCode = HttpCode::from(HttpCode::OK);

Using tryFrom static method

$httpCode = HttpCode::tryFrom(HttpCode::OK);
  • The big difference is, while from will throw an InvalidArgumentException if a constant with the given value does not exist into the declared class, tryFrom will just return null;

Using static magic methods

Any declared constant can be called as a static method to retrieve an Enum instance with the constant value.

$httpCode = HttpCode::OK();

This is the big reason for DocBlocks @method declarations.

Getting the value

$httpCode = HttpCode::OK();
echo $httpCode->get(); //print int 200
echo (string) $httpCode; //print string 200

Comparing

By value

HttpCode::OK()->get() == HttpCode::OK; //true
HttpCode::OK()->get() === HttpCode::OK; //true
HttpCode::OK()->eq(HttpCode::OK); //true

By memory addressing

HttpCode::OK() === HttpCode::OK(); //true
HttpCode::OK()->is(HttpCode::OK()); //true

统计信息

  • 总下载量: 4
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-06-01

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固