Skip to content

DeSmart/php-enum

Repository files navigation

PHP Enum πŸ“š

Latest version Tests Software License

Package provides a strongly typed enums for PHP.

Enumeration class name is used on purpose, to avoid potential issues. There will be native enums in PHP 8.1 πŸŽ‰

There are other great packages implementing enums for PHP. Consider checking them out!

Installation

To install the package via Composer, simply run the following command:

composer require desmart/php-enum

Usage

Example enum definition:

/**
 * @method static Character good()
 * @method static Character evil()
 * @method static Character sometimesGoodSometimesEvil()
 */
class Character extends Enumeration
{
    const GOOD = 'good';
    const EVIL = 'evil';
    const SOMETIMES_GOOD_SOMETIMES_EVIL = 'sometimes_good_or_evil';
}

Create an enum object

$enum = Character::good(); // or Character::fromName('good')

In general, named constructor method name should be a constant name in camelCase.

Few exceptions to this rule are allowed. See test file.

Create an enum object based on available constants' values

$enum = Character::fromValue('sometimes_good_or_evil');

This approach is very convenient when enum objects are created from eg. database.

Comparing enums

Character::good()->equals(Character::fromName('good')); // true
Character::good()->equals(Character::evil());           // false
Character::good()->equals(OtherEnum::someValue());      // false

Changelog

Please see CHANGELOG for more information what has changed recently.

License

The MIT License (MIT). Please see License File for more information.