PHPEnum is an enumeration class library for PHP developers. The idea comes from Java enumeration, and using the PHP features to implement single-value enumeration and multi-value enumeration. PHPEnum runs in most PHP applications.
composer require phpenum/phpenum
Using PhpEnum is very similar to using Java Enum, For example, define an enumeration representing gender.
In Java:
public enum GenderEnum {
MALE(1, "male"),
FEMALE(2, "female");
private Integer id;
private String name;
GenderEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
In PHP:
class GenderEnum extends \PhpEnum\Enum
{
const MALE = [1, 'male'];
const FEMALE = [2, 'female'];
private $id;
private $name;
protected function construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
}
You'll also find a lot of similarities when using enumerations
In Java:
GenderEnum.values(); // enum instance array
GenderEnum.valueOf("FEMALE"); // enum instance
GenderEnum.MALE.equals(GenderEnum.valueOf("MALE")); // true
GenderEnum.MALE.name(); // MALE
GenderEnum.MALE.ordinal(); // 0
GenderEnum.MALE.toString(); // MALE
GenderEnum.MALE.getId(); // 1
GenderEnum.MALE.getName(); // male
In PHP:
GenderEnum::values(); // enum instance array
GenderEnum::valueOf('FEMALE'); // enum instance
GenderEnum::MALE()->equals(GenderEnum::valueOf('MALE')); // true
GenderEnum::MALE()->name(); // MALE
GenderEnum::MALE()->ordinal(); // 0
(string)GenderEnum::MALE(); // MALE
GenderEnum::MALE()->getId(); // 1
GenderEnum::MALE()->getName(); // male
Not only that, PhpEnum also provides advanced functionality in subclasses
GenderEnum::MALE()->idEquals(1); // true
GenderEnum::MALE()->NameEquals('male'); // true
GenderEnum::containsId(1); // 1
GenderEnum::containsName('male'); // 1
GenderEnum::ofId(1); // enum instance
GenderEnum::ofName('male'); // enum instance
PhpEnum supports PHP version 5.6+. The documentation for PHPEnum is available on the Github wiki.
The PHPEnum is open-sourced software licensed under the GPL-3.0 license.