PHPackages                             cuyz/magic-constant - 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. cuyz/magic-constant

ActiveLibrary

cuyz/magic-constant
===================

PHP Magic Constants, even more powerful than an Enum

2.3.0(5mo ago)1458.4k↓29.5%[1 issues](https://github.com/Mopolo/MagicConstant/issues)[1 PRs](https://github.com/Mopolo/MagicConstant/pulls)MITPHPPHP 8.2.\* || 8.3.\* || 8.4.\* || 8.5.\*CI passing

Since Sep 30Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/Mopolo/MagicConstant)[ Packagist](https://packagist.org/packages/cuyz/magic-constant)[ Docs](https://github.com/CuyZ/MagicConstant)[ RSS](/packages/cuyz-magic-constant/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (14)Used By (0)

Magic Constant
==============

[](#magic-constant)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ab3d43e582b7df08e2077e0ecee3c4a0e576de6dc32bb6de5ac3ab5d55281bb4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6375797a2f6d616769632d636f6e7374616e742e737667)](https://packagist.org/packages/cuyz/magic-constant)[![Total Downloads](https://camo.githubusercontent.com/5c40aca71f7519ae6fc62a713a6ce2e37598c72200d255b0234c31206b9f139d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6375797a2f6d616769632d636f6e7374616e742e737667)](https://packagist.org/packages/cuyz/magic-constant)[![Software License](https://camo.githubusercontent.com/074b89bca64d3edc93a1db6c7e3b1636b874540ba91d66367c0e5e354c56d0ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE)

This library allows you to create enum-like classes that support multiple formats for each key.

It helps represent [magic numbers and strings](https://en.wikipedia.org/wiki/Magic_number_(programming)) in code.

Example
-------

[](#example)

Let's say your code has to interact with two services about some contracts.

To represent an active contract:

- Service A uses `active`
- Service B uses `10`

Using a magic constant you declare the following class:

```
use CuyZ\MagicConstant\MagicConstant;

class ContractStatus extends MagicConstant
{
    protected const ACTIVE = [
        self::FORMAT_SERVICE_A => 'active',
        self::FORMAT_SERVICE_B => 10,
    ];

    // Others status...

    public const FORMAT_SERVICE_A = 'a';
    public const FORMAT_SERVICE_B = 'b';
}
```

You can then use it like this:

```
// Instead of doing this:
if ($status === 'active' || $status === 10) {
    //
}

// You can do this:
if ($status->equals(ContractStatus::ACTIVE())) {
    //
}
```

Installation
------------

[](#installation)

```
$ composer require cuyz/magic-constant
```

Usage
-----

[](#usage)

```
use CuyZ\MagicConstant\MagicConstant;

/**
 * You can declare static methods to help with autocompletion:
 *
 * @method static Example FOO()
 * @method static Example BAR()
 * @method static Example FIZ()
 */
class Example extends MagicConstant
{
    // Only protected constants are used as keys
    protected const FOO = 'foo';

    // A key can have multiple possible formats for it's value
    protected const BAR = ['bar', 'BAR', 'b'];

    // You can use an associative array to declare formats
    protected const FIZ = [
        self::FORMAT_LOWER => 'fiz',
        self::FORMAT_UPPER => 'FIZ',
    ];

    // Using constants for formats is not mandatory
    public const FORMAT_LOWER = 'lower';
    public const FORMAT_UPPER = 'upper';
}
```

You can then use the class everywhere:

```
// As a parameter typehint and/or a return typehint
function hello(Example $example): Example {
    //
}

hello(new Example('foo'));

// You can also use constants keys as a static method
hello(Example::BAR());
```

Methods
-------

[](#methods)

#### Get an instance value

[](#get-an-instance-value)

```
echo (new Example('foo'))->getValue(); // 'foo'

// You can specify the desired output format
echo (new Example('FIZ'))->getValue(Example::FORMAT_LOWER); // 'fiz'
```

#### Get an instance key

[](#get-an-instance-key)

```
$constant = new Example('b');

echo $constant->getKey(); // 'BAR'
```

#### Get instances with all possible formats

[](#get-instances-with-all-possible-formats)

```
$constant = new Example('fiz');

echo $constant->getAllFormats(); // [new Example('fiz'), new Example('FIZ')]
```

#### Get all possible values for an instance

[](#get-all-possible-values-for-an-instance)

```
$constant = new Example('BAR');

echo $constant->getAllValues(); // ['bar', 'BAR', 'b']
```

#### Returns a new instance where the value is from the first format

[](#returns-a-new-instance-where-the-value-is-from-the-first-format)

```
$constant = new Example('BAR');

echo $constant->normalize(); // new Example('bar')
```

#### Compares instances

[](#compares-instances)

```
(new Example('foo'))->equals(new Exemple('bar')); // false
(new Example('foo'))->equals(null); // false

(new Example('fiz'))->equals(new Exemple('FIZ')); // true
(new Example('b'))->equals(new Exemple('b')); // true
```

#### Returns true if at least one element is equal

[](#returns-true-if-at-least-one-element-is-equal)

```
$constant = new Example('foo');

$constant->in([new Exemple('bar'), null, 'foo']); // false
$constant->in([new Exemple('foo'), null, 'foo']); // true
```

#### Get all keys for a magic constant class

[](#get-all-keys-for-a-magic-constant-class)

```
Example::keys(); // ['FOO', 'BAR', 'FIZ']
```

#### Get an associative array of possible values

[](#get-an-associative-array-of-possible-values)

```
Example::values();

[
    'FOO' => new Example('foo'),
    'BAR' => new Example('bar'),
    'FIZ' => new Example('fiz'),
];

// You can specify a regex pattern to match certain keys
Example::values('/^F(.+)/');

[
    'FOO' => new Example('foo'),
    'FIZ' => new Example('fiz'),
];
```

#### Get all keys and associated values

[](#get-all-keys-and-associated-values)

```
Example::toArray();

[
    'FOO' => ['foo'],
    'BAR' => ['bar', 'BAR', 'b'],
    'FIZ' => ['fiz', 'FIZ'],
];
```

#### Check if a value is valid

[](#check-if-a-value-is-valid)

```
Example::isValidValue('foo'); // true
Example::isValidValue('hello'); // false
```

#### Check if a key is valid

[](#check-if-a-key-is-valid)

```
Example::isValidKey('BAR'); // true
Example::isValidKey('HELLO'); // false
```

#### Returns the key of any value

[](#returns-the-key-of-any-value)

```
Example::search('foo'); // 'FOO'
Example::search('b'); // 'BAR'
Example::search('hello'); // false
```

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance74

Regular maintenance activity

Popularity36

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 50.8% 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 ~189 days

Recently: every ~408 days

Total

11

Last Release

166d ago

Major Versions

0.3.0 → 1.0.02021-04-01

1.1.0 → 2.0.02023-08-08

PHP version history (5 changes)0.1.0PHP &gt;=7.1.0

2.0.0PHP 8.2.\*

2.1.0PHP 8.2.\* || 8.3.\*

2.2.0PHP 8.2.\* || 8.3.\* || 8.4.\*

2.3.0PHP 8.2.\* || 8.3.\* || 8.4.\* || 8.5.\*

### Community

Maintainers

![](https://www.gravatar.com/avatar/9e50aab3fc5e1aeffab6210c5cbe277a73cfd07ee44da36278bc9b05f41770f7?d=identicon)[Mopolo](/maintainers/Mopolo)

---

Top Contributors

[![renovate[bot]](https://avatars.githubusercontent.com/in/2740?v=4)](https://github.com/renovate[bot] "renovate[bot] (32 commits)")[![Mopolo](https://avatars.githubusercontent.com/u/1319234?v=4)](https://github.com/Mopolo "Mopolo (28 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")

---

Tags

enumphpenumMagic Numbermagic constant

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/cuyz-magic-constant/health.svg)

```
[![Health](https://phpackages.com/badges/cuyz-magic-constant/health.svg)](https://phpackages.com/packages/cuyz-magic-constant)
```

###  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

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

PHP Enums

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

Simple and fast implementation of enumerations with native PHP

49644.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)
