desmart/php-enum

Strongly-typed enum objects for PHP

1.0.0 2021-03-04 07:32 UTC

This package is auto-updated.

Last update: 2024-03-04 14:03:03 UTC


README

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.