# PHP Smart Enum documentation (v8.6.x)

> Canonical: https://pharaonic.dev/packages/php/smart-enum/8.6.x  
> Version: v8.6.x (latest release 8.6.0, 2026-12-01)  
> Install: composer require pharaonic/php-smart-enum  
> Requires: PHP 8.6  
> Repository: https://github.com/Pharaonic/php-smart-enum  
> All versions: https://pharaonic.dev/packages/php/smart-enum/8.6.x.md https://pharaonic.dev/packages/php/smart-enum/8.5.x.md https://pharaonic.dev/packages/php/smart-enum/8.4.x.md https://pharaonic.dev/packages/php/smart-enum/8.3.x.md https://pharaonic.dev/packages/php/smart-enum/8.2.x.md https://pharaonic.dev/packages/php/smart-enum/8.1.x.md

:::badges
- PHP Package {color=blue}
- v8.6.0 {color=green}
- MIT License {color=purple}
:::

# PHP Smart Enum

Smart, lightweight helpers for native PHP enums. Add the `SmartEnum` trait to any enum you already have and every case can answer for itself: `$status->isActive()` for `Active`, `$order->isInProgress()` for `IN_PROGRESS`. You also get helpers for case names, backing values, labels, select options, lookup by case name and comparisons. Native methods (`cases()`, `from()`, `tryFrom()`) stay native, and the package has no base class, no generated code and no runtime dependencies.

:::features
### isActive() for Every Case
Each case gets its own check, named from the case: IN_PROGRESS answers isInProgress().

### Names, Values & Labels
List the case names, the backing values, or the labels of every case.

### Select Options
Map each backing value to a human-readable label, ready for a dropdown.

### Lookup by Case Name
Find a case by its name, the same way from() finds one by its value.

### Comparisons
Compare a case with another case, a case name or a backing value, always strictly.

### Unit & Backed Enums
The same trait works on unit, string-backed and int-backed enums.
:::

:::info Quick Tip
Write case names in the style you like. `IN_PROGRESS`, `InProgress` and `In_Progress` all get the same check, `isInProgress()`, and PHP's own `cases()`, `from()` and `tryFrom()` keep working as before.
:::

## Installation

Install the package with Composer. There is nothing to register or configure.

### Requirements

- PHP 8.6 (`>=8.6 <8.7`)
- No runtime dependencies

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/php-smart-enum
```

Composer autoloads the `Pharaonic\SmartEnum` namespace. The only class you use is the `Pharaonic\SmartEnum\SmartEnum` trait.

:::success Installation Complete
You're all set! Add `use SmartEnum;` to any of your enums.
:::

## Basic Usage

### Add the trait

Import the trait and use it inside a native enum. Backed and unit enums work the same way.

```php title="app/Enums/Status.php"
<?php

namespace App\Enums;

use Pharaonic\SmartEnum\SmartEnum;

enum Status: string
{
    use SmartEnum;

    case Pending = 'pending';
    case Active = 'active';
    case Disabled = 'disabled';
}
```

### Native methods stay native

PHP itself provides these methods. SmartEnum does not redefine or wrap them:

```php
Status::cases();            // [Status::Pending, Status::Active, Status::Disabled]
Status::from('active');     // Status::Active
Status::tryFrom('missing'); // null
```

`from()` and `tryFrom()` exist on backed enums only.

### SmartEnum helpers

The trait adds static helpers on the enum and instance helpers on each case:

```php
Status::names();            // ['Pending', 'Active', 'Disabled']
Status::options();          // ['pending' => 'Pending', 'active' => 'Active', 'disabled' => 'Disabled']
Status::fromName('Active'); // Status::Active

$status = Status::Active;

$status->label();                              // 'Active'
$status->is('active');                         // true
$status->in([Status::Active, Status::Pending]); // true
$status->isActive();                           // true
```

### Ask a case what it is

Every case answers an `is<Case>()` check named after it. The name is built from the case name, so it reads naturally whatever style your cases use:

```php title="app/Enums/OrderStatus.php"
enum OrderStatus: string
{
    use SmartEnum;

    case PENDING = 'pending';
    case IN_PROGRESS = 'in_progress';
    case OUT_FOR_DELIVERY = 'out_for_delivery';
    case Delivered = 'delivered';
}
```

```php
$status = OrderStatus::IN_PROGRESS;

$status->isPending();        // false
$status->isInProgress();     // true
$status->isOutForDelivery(); // false
$status->isDelivered();      // false
```

See [Static Methods](#static-methods), [Instance Methods](#instance-methods) and [Case Checks](#case-checks) for each one.

## Static Methods

Static helpers are called on the enum itself. The examples use the `Status` enum from [Basic Usage](#basic-usage).

### names()

Returns the case names, in declaration order.

```php
Status::names(); // ['Pending', 'Active', 'Disabled']
```

### values()

Returns the backing values, in declaration order.

```php
Status::values(); // ['pending', 'active', 'disabled']
```

On a unit enum it returns the case names instead. See [Unit vs Backed Enums](#unit-and-backed-enums).

### labels()

Returns the case labels, in declaration order.

```php
Status::labels(); // ['Pending', 'Active', 'Disabled']
```

Use `options()` when you need each label keyed by its value.

Each label comes from the case's `label()` method, so [custom labels](#labels) show up here too.

### options()

Returns each case's label, keyed by backing value (`value => label`), for select inputs.

```php
Status::options(); // ['pending' => 'Pending', 'active' => 'Active', 'disabled' => 'Disabled']
```

On a unit enum the keys are the case names.

### fromName() and tryFromName()

Find a case by its case name, the way `from()` and `tryFrom()` find one by its backing value. The name must match exactly, including letter case. `fromName()` throws a `ValueError` when no case matches; `tryFromName()` returns `null`.

```php
Status::fromName('Active');     // Status::Active
Status::tryFromName('active');  // null (that's a backing value, not a name)
Status::fromName('Archived');   // ValueError: No case with name Archived in enum App\Enums\Status.
```

### hasName() and hasValue()

Check whether a case name, or a backing value, exists. Both comparisons are strict.

```php
Status::hasName('Active');  // true
Status::hasValue('active'); // true
Status::hasValue('Active'); // false

Priority::hasValue(1);      // true  (int-backed)
Priority::hasValue('1');    // false (no type juggling)
```

On a unit enum, `hasValue()` checks the case names.

## Instance Methods

Instance helpers are called on a case. The examples use the `Status` enum from [Basic Usage](#basic-usage).

### label()

Returns the human-readable label of the case. By default it is the case name.

```php
Status::Active->label(); // 'Active'
```

See [Labels](#labels) to change it.

### eq()

Strict comparison with another enum case. It only accepts an enum case, and a case of another enum never matches, even with the same name.

```php
Status::Active->eq(Status::Active);   // true
Status::Active->eq(Status::Disabled); // false
```

### is() and isNot()

A comparison that accepts an enum case, a case name, or a backing value (`string` or `int`). `isNot()` is the inverse.

```php
$status = Status::Active;

$status->is(Status::Active);      // true
$status->is('Active');            // true (case name)
$status->is('active');            // true (backing value)
$status->is('ACTIVE');            // false
$status->isNot(Status::Disabled); // true
```

The matching rules:

- An enum case matches only when it is the same case, like `eq()`.
- A string or an int matches when it equals **this case's own** name or backing value.
- Comparison is strict: an int-backed case matches `1`, never `'1'`.
- Strictness applies to the value the method receives. In a file without `declare(strict_types=1)`, PHP itself converts `1.0` or `true` to `1` before `is()` and `hasValue()` see it, so `Priority::High->is(true)` is `true` there. `in()` and `notIn()` reject a float, `bool` or `null` in the list with a `TypeError`.

```php
$priority = Priority::High; // case High = 1

$priority->is(1);   // true
$priority->is('1'); // false
```

:::info A name that is another case's value
Because `is()` looks at the case's own name and value only, a string can match two cases when one case's name is another case's backing value. With `case Open = 'Closed'` and `case Closed = 'Open'`, both `Status::Open->is('Open')` and `Status::Closed->is('Open')` are `true`. Pass the case itself, or use `eq()`, when you need an exact match.
:::

### in() and notIn()

Check whether the case matches any of the given values. Each value is matched like the argument of `is()`, and the list may mix cases, names and values. `notIn()` is the inverse. An empty list never matches.

```php
$status->in([Status::Active, Status::Pending]); // true
$status->in(['active', 'pending']);             // true
$status->notIn([Status::Disabled]);             // true
$status->in([]);                                // false
```

### info()

Returns metadata about the case: its name, backing value and label.

```php
Status::Active->info(); // ['name' => 'Active', 'value' => 'active', 'label' => 'Active']
```

On a unit enum, `value` is the case name.

## Case Checks

Every case gets an `is<Case>()` check, resolved by the trait's `__call()`. It returns `true` only on the case it is named after.

```php
$status = Status::Active;

$status->isActive();   // true
$status->isPending();  // false
$status->isDisabled(); // false
```

You don't declare the checks: adding a case adds its check.

### From case name to check

| Case | Check |
| --- | --- |
| `Active` | `isActive()` |
| `PENDING` | `isPending()` |
| `IN_COOKING` | `isInCooking()` |
| `IN_PROGRESS` | `isInProgress()` |
| `OUT_FOR_DELIVERY` | `isOutForDelivery()` |
| `InProgress` | `isInProgress()` |
| `In_Progress` | `isInProgress()` |
| `onHold` | `isOnHold()` |
| `HTTPError` | `isHTTPError()` |
| `Level2` | `isLevel2()` |

```php
$status = OrderStatus::IN_PROGRESS;

$status->isInProgress();     // true
$status->isOutForDelivery(); // false
```

### How check names are built

The check name is `is` followed by the case name, with each underscore-separated word capitalized:

- A word written entirely in upper case is title-cased: `PENDING` becomes `isPending`, `IN_COOKING` becomes `isInCooking`.
- Any other word keeps its letters and gets an upper-case first letter: `onHold` becomes `isOnHold`, `HTTPError` becomes `isHTTPError`, `Level2` becomes `isLevel2`.

### Names that are not checks

Check names are matched exactly, letter case included. Each call below throws `Error: Call to undefined method`:

| Call | Why it fails | Write instead |
| --- | --- | --- |
| `isArchived()` | No case is named `Archived` | Add the case, or use `is('Archived')` for input you don't control |
| `pending()` | Checks start with `is` | `isPending()` |
| `hasPending()` | Only the `is` prefix makes a check | `isPending()` |
| `IsPending()` | The prefix is lower-case `is` | `isPending()` |
| `isPENDING()` | The raw case name is not used | `isPending()` |
| `isIN_COOKING()` | Underscores are removed | `isInCooking()` |
| `isinprogress()` | Each word starts with a capital letter | `isInProgress()` |
| `isonHold()` | The first letter after `is` is a capital | `isOnHold()` |
| `isHttpError()` | Mixed-case words keep their letters | `isHTTPError()` |
| `secret()` | A `protected` or `private` enum method can't be called from outside | Make it `public` |

```php
OrderStatus::PENDING->isPENDING();
// Error: Call to undefined method App\Enums\OrderStatus::isPENDING()
```

### Arguments are ignored

A check takes no arguments. Anything you pass is ignored, so `$status->isActive('anything', 1)` is the same as `$status->isActive()`.

### Ambiguous checks

When two cases produce the same check name, for example `IN_PROGRESS` and `InProgress` (both `isInProgress`), calling that check throws a `BadMethodCallException` that names both cases. The checks of the other cases keep working.

```php
Task::Done->isInProgress();
// BadMethodCallException: Call to ambiguous method App\Enums\Task::isInProgress(): matches cases IN_PROGRESS, InProgress.
```

Use `is()` with the case itself when the names collide: `$task->is(Task::InProgress)`.

### Your own methods win

A method you declare in the enum is always called directly, never through `__call()`. If you declare `isActive()` yourself, your version is used.

A call that matches no check throws `Error: Call to undefined method`, the same error PHP throws without the trait. That includes your enum's own `protected` and `private` methods: calling one from outside the enum fails, as visibility says it should.

### IDE and static analysis support

IDEs and PHPStan can't see `__call()` checks on their own. Declare them with `@method` tags on the enum:

```php title="app/Enums/Status.php"
/**
 * @method bool isPending()
 * @method bool isActive()
 * @method bool isDisabled()
 */
enum Status: string
{
    use SmartEnum;

    case Pending = 'pending';
    case Active = 'active';
    case Disabled = 'disabled';
}
```

## Labels

`label()` returns the case name by default. `labels()`, `options()` and `info()` all read their labels from `label()`, so changing it once changes them all.

### Per enum: override label()

Declare `label()` in the enum. A method declared in the enum takes priority over the trait's.

```php title="app/Enums/Status.php"
enum Status: string
{
    use SmartEnum;

    case Pending = 'pending';
    case Active = 'active';
    case Disabled = 'disabled';

    public function label(): string
    {
        return match ($this) {
            self::Pending => 'Waiting for review',
            self::Active => 'Active',
            self::Disabled => 'Disabled',
        };
    }
}

Status::options(); // ['pending' => 'Waiting for review', 'active' => 'Active', 'disabled' => 'Disabled']
```

### App-wide: the smart_enum_label() hook

When a global function named `smart_enum_label()` exists, the trait's `label()` calls it with the case. If it returns a string, that string is the label. If it returns anything else, such as `null`, the case name is used.

```php title="src/helpers.php"
<?php

use App\Enums\Status;

function smart_enum_label(UnitEnum $case): ?string
{
    if ($case instanceof Status) {
        return ucwords(strtolower(str_replace('_', ' ', $case->name)));
    }

    return null; // other enums keep their case names
}
```

The function must be loaded before any label is read. Load it with Composer's `files` autoloading:

```json title="composer.json"
{
    "autoload": {
        "files": ["src/helpers.php"]
    }
}
```

:::info Translations
The hook is a good place to translate labels, for example by looking the case up in your translation files. An enum that overrides `label()` itself does not call the hook.
:::

## Unit vs Backed Enums

PHP has two kinds of enums, and SmartEnum supports both:

```php title="app/Enums/Priority.php"
enum Priority: int   // backed: every case has a value
{
    use SmartEnum;

    case Low = 0;
    case High = 1;
}
```

```php title="app/Enums/Direction.php"
enum Direction       // unit: cases have a name only
{
    use SmartEnum;

    case Up;
    case Down;
}
```

Helpers that only need the case name work the same on both: `names()`, `labels()`, `fromName()`, `tryFromName()`, `hasName()`, `label()`, `eq()` and the `is<Case>()` checks.

A unit enum has no backing values, so the helpers that use them fall back to the case name:

| Helper | Backed enum | Unit enum |
| --- | --- | --- |
| `values()` | Backing values | Case names |
| `options()` | `value => label` | `name => label` |
| `hasValue($value)` | Checks the backing values | Checks the case names |
| `info()['value']` | The backing value | The case name |
| `is()` / `in()` | Case, name or value | Case or name |

```php
Direction::values();         // ['Up', 'Down']
Direction::options();        // ['Up' => 'Up', 'Down' => 'Down']
Direction::hasValue('Up');   // true
Direction::Up->info();       // ['name' => 'Up', 'value' => 'Up', 'label' => 'Up']
```

:::info Native methods on unit enums
PHP does not define `from()` or `tryFrom()` on unit enums. Use `fromName()` / `tryFromName()` to look up a unit case by name.
:::

## API Reference

All methods are declared on the `Pharaonic\SmartEnum\SmartEnum` trait.

### Static methods

| Method | Description | Returns |
| --- | --- | --- |
| `names()` | Case names | `array` (list of `string`) |
| `labels()` | Case labels | `array` (list of `string`) |
| `values()` | Backing values; case names on a unit enum | `array` (list of `int\|string`) |
| `options()` | Labels keyed by backing value; by case name on a unit enum | `array` (`int\|string => string`) |
| `fromName(string $name)` | The case with this case name, or a `ValueError` | `static` |
| `tryFromName(string $name)` | The case with this case name, or `null` | `?static` |
| `hasName(string $name)` | Whether a case with this name exists | `bool` |
| `hasValue(string\|int $value)` | Whether a case with this backing value exists; this name on a unit enum | `bool` |

### Instance methods

| Method | Description | Returns |
| --- | --- | --- |
| `label()` | Human-readable label of the case | `string` |
| `eq(UnitEnum $enum)` | Whether the given case is this case | `bool` |
| `is(UnitEnum\|string\|int $value)` | Matches this case, its name or its backing value | `bool` |
| `isNot(UnitEnum\|string\|int $value)` | Inverse of `is()` | `bool` |
| `in(array $values)` | Matches any of the given values | `bool` |
| `notIn(array $values)` | Inverse of `in()` | `bool` |
| `info()` | `['name' => …, 'value' => …, 'label' => …]`; `value` is the case name on a unit enum | `array` |
| `is<Case>()` | Whether this is the named case, through `__call()` | `bool` |

### Exceptions

| Thrown by | Exception | When |
| --- | --- | --- |
| `fromName()` | `ValueError` | No case has the given name |
| `is<Case>()` | `BadMethodCallException` | Two cases produce the same check name |
| `__call()` | `Error` | The name is not a check, or is a non-public method called from outside the enum |

### Label hook

| Function | Description | Returns |
| --- | --- | --- |
| `smart_enum_label(UnitEnum $case)` | Optional global function you define; used by `label()` when it returns a string | `?string` |

### Native methods (provided by PHP)

| Method | Description | Available on |
| --- | --- | --- |
| `cases()` | All cases, in declaration order | Unit and backed enums |
| `from(int\|string $value)` | The case with this backing value, or a `ValueError` | Backed enums |
| `tryFrom(int\|string $value)` | The case with this backing value, or `null` | Backed enums |

## Examples

### 1. Branching on a status

Read the checks like plain English when the code depends on the current case.

```php title="src/Orders/OrderNotifier.php"
public function notify(Order $order): void
{
    if ($order->status->isOutForDelivery()) {
        $this->sms->send($order->phone, 'Your order is on its way.');
    }

    if ($order->status->isDelivered()) {
        $this->mailer->send(new OrderDelivered($order));
    }
}
```

### 2. A select input

Build `<option>` tags from `options()`, which maps each backing value to its label.

- ===Enum

  ```php title="app/Enums/Status.php"
  <?php

  namespace App\Enums;

  use Pharaonic\SmartEnum\SmartEnum;

  enum Status: string
  {
      use SmartEnum;

      case Pending = 'pending';
      case Active = 'active';
      case Disabled = 'disabled';
  }
  ```

- ===Template

  ```php title="templates/status-select.php"
  <select name="status">
      <?php foreach (\App\Enums\Status::options() as $value => $label): ?>
          <option value="<?= htmlspecialchars((string) $value) ?>"><?= htmlspecialchars($label) ?></option>
      <?php endforeach ?>
  </select>
  ```

### 3. Validating input

Check a submitted value before converting it with PHP's own `from()`.

```php title="src/Http/UpdateStatus.php"
if (! Status::hasValue($input['status'])) {
    throw new InvalidArgumentException('Unknown status.');
}

$status = Status::from($input['status']);
```

### 4. Guarding a state change

Allow an action only for some cases.

```php title="src/Accounts/Account.php"
public function suspend(): void
{
    if ($this->status->notIn([Status::Pending, Status::Active])) {
        throw new LogicException('Only pending or active accounts can be suspended.');
    }

    $this->status = Status::Disabled;
}
```

### 5. Configuration by case name

Read a case name from configuration or the environment and resolve it, with a fallback.

```php title="config/app.php"
$defaultStatus = Status::tryFromName(getenv('DEFAULT_STATUS') ?: '') ?? Status::Pending;
```

### 6. Serializing for an API

Return the case metadata from `info()` in a JSON response.

```php title="src/Http/StatusController.php"
echo json_encode(array_map(
    static fn (Status $status): array => $status->info(),
    Status::cases(),
));
```

## Troubleshooting

### Error: Call to undefined method Status::isactive()

Check names are matched exactly, including letter case: write `isActive()`, not `isactive()` or `IsActive()`. For a case named `IN_COOKING`, the check is `isInCooking()`. See [How check names are built](#case-checks).

### BadMethodCallException: Call to ambiguous method

Two of your cases produce the same check name, such as `IN_PROGRESS` and `InProgress`. Rename one of them, or compare with `$task->is(Task::InProgress)`.

### PHPStan or my IDE reports isActive() as undefined

`is<Case>()` checks are resolved at runtime by `__call()`. Add `@method bool isActive()` tags to the enum's docblock, as shown in [IDE and static analysis support](#case-checks).

### is('1') returns false on an int-backed enum

Matching is strict. Pass the integer: `$priority->is(1)`. Convert request input first, for example with `Priority::tryFrom((int) $input)`.

### My smart_enum_label() function is ignored

The function must be global (no namespace), loaded before the label is read (use Composer `files` autoloading), and return a string. An enum that declares its own `label()` does not call it.

### My own label() method is used instead of the trait's

PHP gives a method declared in the enum priority over a method from a trait. This is expected: if your enum declares `label()`, `is()` or another method with the same name, your version wins. Keep the same signature so code that relies on the trait keeps working.

### Trait method collision with another trait

If another trait used by the same enum also declares, for example, `is()`, PHP throws a fatal error. Resolve it with `insteadof`:

```php title="app/Enums/Status.php"
enum Status: string
{
    use SmartEnum, OtherTrait {
        SmartEnum::is insteadof OtherTrait;
    }

    case Active = 'active';
}
```

### Call to undefined method Direction::from()

`from()` and `tryFrom()` are native PHP methods that only exist on backed enums. For a unit enum, look cases up by name with `fromName()` / `tryFromName()`.

### Composer refuses to install the package

This release line requires PHP 8.6 (`>=8.6 <8.7`). Each PHP minor from 8.1 has its own release line, and Composer installs the one that matches your PHP; 8.1 is the version that introduced native enums. Check `php -v` and the `config.platform.php` setting in your `composer.json`.

## Upgrade Guide

Smart Enum has one release line per PHP version, and every line has the same trait, methods and results. This page covers the `8.6.x` line, for PHP 8.6.

### Patch Releases

Patch releases such as `8.6.0` to `8.6.1` never break your code. Update with:

```bash no-line-numbers
composer update pharaonic/php-smart-enum
```

Results change only to fix a bug, and every such change is listed in the changelog.

### Moving To Another PHP Version

No code changes are needed. Composer picks the line that matches your PHP version, so after upgrading PHP run `composer update pharaonic/php-smart-enum`.

The constraint that `composer require` writes (for example `^8.6`) already allows the newer lines. If you pinned a line with a tilde constraint such as `~8.6.0`, widen it first, or Composer stays on `8.6.x` and cannot install on the new PHP version.

### Changelog

Every release is listed in the [changelog](https://github.com/Pharaonic/php-smart-enum/blob/8.6.x/CHANGELOG.md) and on the [GitHub releases](https://github.com/Pharaonic/php-smart-enum/releases) page.
