myclabs/php-enum
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
The MyCLabs PHP Enum package provides a way for PHP developers to use enumerations, a concept not integrated into the PHP core, avoiding the need to separately install the SplEnum extension. Enumerations allow you to define a type that can be one of several different values, providing more type-safety than using class constants. This package enables developers to use an enumeration as a parameter type or return type, enrich the enumeration with methods, extend the enumeration to add new values, and obtain a list of all possible values.
To use the MyCLabs PHP Enum package, start by installing it into your PHP project using composer with the command composer require myclabs/php-enum
. Then, declare an enumeration, which extends MyCLabs\Enum\Enum
, using private constants to describe the possible values.
use MyCLabs\Enum\Enum;
/**
* Action enum
*/
final class Action extends Enum
{
private const VIEW = 'view';
private const EDIT = 'edit';
}
To use the enumeration, you can use the statically implemented methods to quickly access an enum value, such as Action::VIEW()
. It's also possible to use enums as a parameter type in functions.
$action = Action::VIEW();
function setAction(Action $action) {
// ...
}
The documentation for the MyCLabs PHP Enum package can be found right in the README file of the repository. Here, you'll find details about the package's constructor, built-in methods and static methods. For instance, the __construct()
method ensures the value exists in the enum, while the __toString()
method allows an enum value to be output as a string.
The static methods provide a variety of utilities such as from()
to create an enum instance, toArray()
to return all possible values, keys()
to return all possible keys (names of constants), values()
to return instances for all constants, among others. It also includes methods to verify value validity (isValid()
, isValidKey()
, assertValidValue()
) and search for a key (search()
).
Should your project be running PHP 8.1 or higher, you should consider using the newly introduced native enums instead of this library. A comparison and guide to migrating to native enums is provided within the documentation.