PHPackages                             ynkt/enum-like - 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. ynkt/enum-like

AbandonedArchivedLibrary

ynkt/enum-like
==============

Implementation like Enum with PHP

v1.1.0(5y ago)13MITPHPPHP &gt;=7.4

Since Jan 5Pushed 5y ago1 watchersCompare

[ Source](https://github.com/ynkt/enum)[ Packagist](https://packagist.org/packages/ynkt/enum-like)[ RSS](/packages/ynkt-enum-like/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (5)Dependencies (1)Versions (6)Used By (0)

Implementation like Enum with PHP
=================================

[](#implementation-like-enum-with-php)

Table of Contents
=================

[](#table-of-contents)

- [Why](#why)
- [Requirements](#requirements)
- [Install](#install)
- [Usage](#usage)
- [Tips](#tips)
- [Examples](#examples)

Why
===

[](#why)

I created this library to allow Enum to be used in many situations.

This library has the following advantages:

- Multiple values can be declared per enumerator
- You can declare Enum from various data sources, such as class constant, DB, or configuration file

Requirements
============

[](#requirements)

- PHP ^7.4

Install
=======

[](#install)

```
composer require ynkt/enum
```

Usage
=====

[](#usage)

`Enum` is an abstract class needs to be extended to use.

Basic Declaration
-----------------

[](#basic-declaration)

The following code uses class constant for the declaring Enum.

**Notes**

**- Use protected visibility when writing the `__constructor()`**

**- Do not declare the methods that has the same name of the enumerator name**

```
use Ynkt\Enum\Enum;

/**
 * Class Status
 */
class Status extends Enum
{
    private const READY = 'Ready';
    private const IN_PROGRESS = 'In Progress';
    private const DONE = 'Done';

    private string $text;

    // The argument of __constructor() is automatically assigned to the value of the enumerator
    protected function __construct(string $text) { $this->text = $text; }

    public function text(): string { return $this->text; }
}
```

Static methods
--------------

[](#static-methods)

```
// Provided by this library
Status::values(); // Returns instances of the Enum class of all Enumerators
Status::first(); // Returns the first instance
Status::first(callable $closure); // Returns the first instance that passes a given truth
Status::has(callable $closure); // Tests an instance exists that passes a given truth

// Provided by the user declaration
// This library automatically provide the static method whose name is same of the enumerators name.
// The following methods return an Enum instance.
Status::READY();
Status::IN_PROGRESS();
Status::DONE();
```

Static methods that has the same name as the enumerator name are implemented by `__callStatic()`.

Therefore, if you care about the IDE auto completion, I recommend using the phpdoc as follows:

```
/**
 * Class Status
 *
 * @method static self READY()
 * @method static self IN_PROGRESS()
 * @method static self DONE()
 */
class Status extends Enum
{
    private const READY = 'Ready';
    private const IN_PROGRESS = 'In Progress';
    private const DONE = 'Done';

    // ...
}
```

Instance methods
----------------

[](#instance-methods)

```
$status = Status::READY();

// Provided by this library
$status->name(); // Returns the name of the current enumerator (e.g.:'READY')
$status->ordinal(); // Returns the ordinal of the current enumerator (e.g.:0)
$status->declaringClass(); // Returns the declaring class of the current enumerator (e.g.:'Status')
$status->equals(Status::Ready()); // Tests enum instances are equal (e.g.:true)

// Provided by the user declaration
$status->text(); // Returns 'Ready'
```

Type hint
---------

[](#type-hint)

You can use classes that inherit from Enum for type hints.

```
function updateStatus(Status $status){
  // ...
}

updateStatus(Status::READY());
```

How to declare the multiple values per enumerator
-------------------------------------------------

[](#how-to-declare-the-multiple-values-per-enumerator)

If you want to declare the multiple values per enumerator, you can assign an array.

```
class Color extends Enum
{
    private const RED = ['#FF0000', [255, 0, 0]];
    private const BLUE = ['#0000FF', [0, 0, 255]];
    private const BLACK = ['#000000', [0, 0, 0]];

    // The argument of __constructor() is automatically assigned to the value of the enumerator
    protected function __construct(string $code, array $rgb) {}

    // ...
}
```

How to declare the Enum from various data sources
-------------------------------------------------

[](#how-to-declare-the-enum-from-various-data-sources)

If you want to declare an Enum based on data that is not a class constant, you can overwrite `getConstants()`.

The following two ways of declaration are equivalent.

```
class ColorFromDataSource extends Enum
{
    /**
     * @overwrite
     */
    protected static function getConstants(string $class): array
    {
        return [
            'RED'   => ['#FF0000', [255, 0, 0]],
            'BLUE'  => ['#0000FF', [0, 0, 255]],
            'BLACK' => ['#000000', [0, 0, 0]],
        ];
    }

    // ...
}
```

```
class Color extends Enum
{
    private const RED = ['#FF0000', [255, 0, 0]];
    private const BLUE = ['#0000FF', [0, 0, 255]];
    private const BLACK = ['#000000', [0, 0, 0]];

    // ...
}
```

Tips
====

[](#tips)

If you want to get an instance by Identifier or something
---------------------------------------------------------

[](#if-you-want-to-get-an-instance-by-identifier-or-something)

Using an identifier as a way to get an instance is a common pattern. So, as a way to achieve this, I have prepared `ByIdTrait` to get an instance based on the ID.

```
class DayOfWeek extends Enum
{
    use ByIdTrait;

    private const MONDAY = 1;
    private const TUESDAY = 2;

    private int $id;

    public function id(): int { return $this->id; }

    // ...
}

// You can use byId() to get the Enum instance.
$dayOfWeek = DayOfWeek::byId(1);
$dayOfWeek->equals(DayOfWeek::MONDAY()); // Returns true
```

I think the implementation of the `ByIdTrait` will be helpful when you get an instance based on some identifiers.

Examples
========

[](#examples)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity61

Established project with proven stability

 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 ~72 days

Total

5

Last Release

2033d ago

PHP version history (2 changes)v1.0.0-alpha1PHP &gt;=7.2

v1.1.0PHP &gt;=7.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/9029986?v=4)[Nakata Yudai](/maintainers/ynkt)[@ynkt](https://github.com/ynkt)

---

Top Contributors

[![ynkt](https://avatars.githubusercontent.com/u/9029986?v=4)](https://github.com/ynkt "ynkt (67 commits)")

---

Tags

enumphpenum

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ynkt-enum-like/health.svg)

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

###  Alternatives

[myclabs/php-enum

PHP Enum implementation

2.7k227.9M637](/packages/myclabs-php-enum)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[dasprid/enum

PHP 7.1 enum implementation

379146.0M11](/packages/dasprid-enum)[spatie/enum

PHP Enums

84429.1M68](/packages/spatie-enum)[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49444.8M97](/packages/marc-mabe-php-enum)[fresh/doctrine-enum-bundle

Provides support of ENUM type for Doctrine2 in Symfony applications.

4636.8M12](/packages/fresh-doctrine-enum-bundle)

PHPackages © 2026

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