PHPackages                             ekvedaras/php-enum - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ekvedaras/php-enum

AbandonedLibrary[Utility &amp; Helpers](/categories/utility)

ekvedaras/php-enum
==================

PHP enum implementation

v1.3.0(5y ago)242.1k↓33.3%2MITPHPPHP &gt;=7.2

Since Aug 30Pushed 5y ago1 watchersCompare

[ Source](https://github.com/ekvedaras/php-enum)[ Packagist](https://packagist.org/packages/ekvedaras/php-enum)[ Docs](https://github.com/ekvedaras/php-enum)[ RSS](/packages/ekvedaras-php-enum/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (8)Used By (2)

PHP Enum
========

[](#php-enum)

[![Tests](https://github.com/ekvedaras/php-enum/workflows/run-tests/badge.svg)](https://github.com/ekvedaras/php-enum/workflows/run-tests/badge.svg)[![Code Coverage](https://camo.githubusercontent.com/6131039bd2e2f4672d9908fb01599885f13e1d0167c9a7ed4a372ad7a0a96c4b/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f67682f656b766564617261732f7068702d656e756d2f6d61696e3f7374796c653d666c6174)](https://app.codecov.io/gh/ekvedaras/php-enum)[![Software License](https://camo.githubusercontent.com/f251623e510f5909f16ae3f4e6e548dac11340b9fde1a99be26b015b39272c00/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c6174)](LICENSE)[![Latest Version on Packagist](https://camo.githubusercontent.com/8aea191829527f327d1cfd58b7d9e7a1c8e6e0b03b72c3e5d4736194ee7957be/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656b766564617261732f7068702d656e756d2e7376673f7374796c653d666c6174)](https://packagist.org/packages/ekvedaras/php-enum)[![Total Downloads](https://camo.githubusercontent.com/8c8a9b95c89bfb477ff62baaeb75ee8026abd770ecffd7d3d7c6a14629498c80/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656b766564617261732f7068702d656e756d2e7376673f7374796c653d666c6174)](https://packagist.org/packages/ekvedaras/php-enum)

[![](logo.svg)](logo.svg)

[![Twitter Follow](https://camo.githubusercontent.com/ba5fadb851bf6fcd83fb90c7afb6f1d23e25ba9424c820cc5d011820079216a4/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f666f6c6c6f772f656b766564617261733f7374796c653d706c6173746963)](https://camo.githubusercontent.com/ba5fadb851bf6fcd83fb90c7afb6f1d23e25ba9424c820cc5d011820079216a4/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f666f6c6c6f772f656b766564617261733f7374796c653d706c6173746963)

Big thanks [happy-types/enumerable-type](https://packagist.org/packages/happy-types/enumerable-type) for the original idea. Take a look if it suits your needs better.

This package adds `meta` field, provides a few more methods like `options`, `keys`, `json`, etc. and there are simple php array, `illuminate/collection`, `arrayy` and `doctrine` collection implementations to choose from.

Benefits
--------

[](#benefits)

- Enums in general allow to avoid [magic values](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants)
- By type hinting forces only allowed values to be passed to methods (or returned)
- Easy way to list all possible values
- More feature rich and flexible then other enum implementations
- Works with strict (`===`) operator
- IDE friendly, so auto complete, usage analysis and refactorings all work

Defining enums
--------------

[](#defining-enums)

Create enums by extending one of:

- `EKvedaras\PHPEnum\PHPArray\Enum`
- `EKvedaras\PHPEnum\Illuminate\Collection\Enum`
- `EKvedaras\PHPEnum\Arrayy\Enum`
- `EKvedaras\PHPEnum\Doctrine\Enum`

```
use EKvedaras\PHPEnum\PHPArray\Enum;

class PaymentStatus extends Enum
{
    /**
     * @return static
     */
    final public static function pending(): self
    {
        return static::get('pending', 'Payment is pending');
    }

    /**
     * @return static
     */
    final public static function completed(): self
    {
        return static::get('completed', 'Payment has been processed');
    }

    /**
     * @return static
     */
    final public static function failed(): self
    {
        return static::get('failed', 'Payment has failed');
    }
}
```

Integers can be used as IDs instead of string values if you prefer.

Usage
-----

[](#usage)

### Retrieving and comparing enum values

[](#retrieving-and-comparing-enum-values)

```
// Retrieving value statically
$status1 = PaymentStatus::completed();

// Retrieving value dynamically from ID
$status2 = PaymentStatus::from('completed');

// Strict comparison is supported
var_dump($status1 === $status2); // true
```

### Accessing value properties

[](#accessing-value-properties)

```
$status = PaymentStatus::copmleted();

$status->id();   // 'completed'
$status->name(); // 'Payment has been processed'
$status->meta(); // null
```

### Listing enum values

[](#listing-enum-values)

There are two implementations provided:

#### PHP array

[](#php-array)

To use PHP array your enums should extend `EKvedaras\PHPEnum\PHPArray\Enum` class

```
var_dump(PaymentStatus::enum());
/*
array(3) {
  'pending' =>
  class PaymentStatus#12 (3) {
    protected $id =>
    string(7) "pending"
    protected $name =>
    string(18) "Payment is pending"
    protected $meta =>
    NULL
  }
  'completed' =>
  class PaymentStatus#363 (3) {
    protected $id =>
    string(9) "completed"
    protected $name =>
    string(26) "Payment has been processed"
    protected $meta =>
    NULL
  }
  'failed' =>
  class PaymentStatus#13 (3) {
    protected $id =>
    string(6) "failed"
    protected $name =>
    string(18) "Payment has failed"
    protected $meta =>
    NULL
  }
}
 */
```

```
var_dump(PaymentStatus::options());
/*
array(3) {
  'pending' =>
  string(18) "Payment is pending"
  'completed' =>
  string(26) "Payment has been processed"
  'failed' =>
  string(18) "Payment has failed"
}
*/
```

```
var_dump(PaymentStatus::keys());
/*
array(3) {
  [0] =>
  string(7) "pending"
  [1] =>
  string(9) "completed"
  [2] =>
  string(6) "failed"
}
*/
```

```
var_dump(PaymentStatus::json()); // Will include meta if defined
```

```
{
    "pending": {
        "id": "pending",
        "name": "Payment is pending"
    },
    "completed": {
        "id": "completed",
        "name": "Payment has been processed"
    },
    "failed": {
        "id": "failed",
        "name": "Payment has failed"
    }
}
```

```
var_dump(PaymentStatus::jsonOptions());
```

```
{
    "pending": "Payment is pending",
    "completed": "Payment has been processed",
    "failed": "Payment has failed"
}
```

#### Illuminate Collection

[](#illuminate-collection)

**Either `illuminate/support` or `illuminate/collections` package is required which is not installed by default.**

To use Illuminate Collection your enums should extend `EKvedaras\PHPEnum\Illuminate\Collection\Enum` class.

The only difference is `enum`, `options` and `keys` methods will return `Collection` instances instead of arrays. The rest works exactly the same.

```
var_dump(PaymentStatus::enum());
/*
class Illuminate\Support\Collection#362 (1) {
  protected $items =>
  array(3) {
    'pending' =>
    class PaymentStatus#12 (3) {
      protected $id =>
      string(7) "pending"
      protected $name =>
      string(18) "Payment is pending"
      protected $meta =>
      NULL
    }
    'completed' =>
    class PaymentStatus#363 (3) {
      protected $id =>
      string(9) "completed"
      protected $name =>
      string(26) "Payment has been processed"
      protected $meta =>
      NULL
    }
    'failed' =>
    class PaymentStatus#13 (3) {
      protected $id =>
      string(6) "failed"
      protected $name =>
      string(18) "Payment has failed"
      protected $meta =>
      NULL
    }
  }
}
 */
```

```
var_dump(PaymentStatus::options());
/*
class Illuminate\Support\Collection#368 (1) {
  protected $items =>
  array(3) {
    'pending' =>
    string(18) "Payment is pending"
    'completed' =>
    string(26) "Payment has been processed"
    'failed' =>
    string(18) "Payment has failed"
  }
}
*/
```

```
var_dump(PaymentStatus::keys());
/*
class Illuminate\Support\Collection#13 (1) {
  protected $items =>
  array(3) {
    [0] =>
    string(7) "pending"
    [1] =>
    string(9) "completed"
    [2] =>
    string(6) "failed"
  }
}
*/
```

### Meta

[](#meta)

Meta field is intentionally left as mixed type as it could be used for various reasons. For example linking enum options with a specific implementation:

```
use EKvedaras\PHPEnum\PHPArray\Enum;

class PaymentMethod extends Enum
{
    final public static function payPal(): self
    {
        return static::get('paypal', 'PayPal', PayPalHandler::class);
    }

    final public static function stripe(): self
    {
        return static::get('stripe', 'Stripe', StripeHandler::class);
    }
}
```

Resolving payment handler in Laravel:

```
$method = PaymentMethod::from($request['method_id']);

$handler = app($method->meta());
```

Meta could also be used as a more in detail description of each option that could be displayed to users or some other object linking other classes, resources together.

Furthermore, in some cases it is useful to resolve enum option from meta. That is also possible:

```
$method = PaymentMethod::fromMeta(StripeHandler::class);
```

Things to know
--------------

[](#things-to-know)

### `final public static function`

[](#final-public-static-function)

Only methods marked as `final public static` will be considered as possible values of enum. Other methods are still there, but they will not be returned in `enum` / `keys` / `options`, etc. results and won't be considered as valid values. However, this allows to extend enums and make them more useful. For example:

```
use EKvedaras\PHPEnum\Illuminate\Collection\Enum;
use Illuminate\Support\Collection;

class PaymentMethods extends Enum
{
    /**
     * @return static
     */
    final public static function payPal(): self
    {
        return static::get('paypal', 'PayPal');
    }

    /**
     * @return static
     */
    final public static function stripe(): self
    {
        return static::get('stripe', 'Stripe');
    }

    /**
     * @return static
     */
    final public static function mollie(): self
    {
        return static::get('mollie', 'Mollie');
    }

    /**
     * Returns only enabled payment methods. Useful for validation or rendering payments UI
     * @return Collection|static[]
     */
    public static function enabled(): Collection
    {
        return static::enum()->only(config('payments.enabled'));
    }
}
```

### `from($id)` only allows valid IDs

[](#fromid-only-allows-valid-ids)

Well, this is expected. Calling `PaymentMethod::from('ideal')` will throw `OutOfBoundsException`.

### No serialization

[](#no-serialization)

Enum object instances cannot be serialized. Deserialized objects would get a different address in memory therefore, `===` would no longer work. Calling `serialize(PaymentMethod::stripe())` will throw a `RuntimeException`.

As a workaround it is better to store the ID instead of object itself. You still get the bonus of setters only accepting valid values.

```
class Payment
{
    /** @var string */
    private $method;

    public function setMethod(PaymentMethod $method)
    {
        $this->method = $method->id();
    }

    public function getMethod(): PaymentMethod
    {
        return PaymentMethod::from($this->method);
    }
}
```

### Don't mix implementations

[](#dont-mix-implementations)

Enum instances cache is stored in a static variable. Choose one implementation for your project and stick to it, otherwise you may unexpectedly get errors because types don't match.

You may create your own project enum class and extend your chosen implementation, so if it ever needs to be changed it can be done in one place only (if storage APIs match).

Related packages
----------------

[](#related-packages)

- [ekvedaras/laravel-enum](https://packagist.org/packages/ekvedaras/laravel-enum)
- [ekvedaras/doctrine-enum](https://packagist.org/packages/ekvedaras/doctrine-enum)

Changelog
---------

[](#changelog)

See changes in changelog files:

- [v1 changelog](CHANGELOG-1.x.md)

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~20 days

Recently: every ~30 days

Total

7

Last Release

1965d ago

PHP version history (2 changes)v1.0.0PHP ^7.2

v1.3.0PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/967a95775e4f15cc9f30962b5ed8b24c9a60dd96cf57b78993f74c35e1dc9272?d=identicon)[ekvedaras](/maintainers/ekvedaras)

---

Top Contributors

[![ekvedaras](https://avatars.githubusercontent.com/u/3586184?v=4)](https://github.com/ekvedaras "ekvedaras (35 commits)")

---

Tags

enumenum-implementationsphpphp-enumphpenumenumerableekvedaras

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ekvedaras-php-enum/health.svg)

```
[![Health](https://phpackages.com/badges/ekvedaras-php-enum/health.svg)](https://phpackages.com/packages/ekvedaras-php-enum)
```

###  Alternatives

[spatie/enum

PHP Enums

84529.1M68](/packages/spatie-enum)[kongulov/interact-with-enum

Trait for convenient use of ENUM in PHP

3052.3k2](/packages/kongulov-interact-with-enum)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2516.7k](/packages/iteks-laravel-enum)[ducks-project/spl-types

Polyfill Module for SplType PHP extension. This extension aims at helping people making PHP a stronger typed language and can be a good alternative to scalar type hinting. It provides different typehandling classes as such as integer, float, bool, enum and string

1032.4k](/packages/ducks-project-spl-types)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
