nilay-jp / php-enum
Enum implementation for PHP.
v2.0.0
2021-03-31 12:01 UTC
Requires
- php: ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpstan/phpstan: ^0.12.25
- phpunit/phpunit: ^9.1
README
Enum implementation for PHP.
Example
Simple example.
<?php // "HIGH" var_dump(Height::HIGH()->name()); // true var_dump(Height::HIGH()->equals(Height::HIGH())); // false var_dump(Height::HIGH()->equals(Height::MEDIUM())); // 0 | 1 | ... | n var_dump(Height::HIGH()->ordinal()); // Height.MEDIUM var_dump(Height::valueOf("MEDIUM")); // Array<Height> [Height.HIGH, Height.MEDIUM, Height.LOW] var_dump(Height::values());
namespace com.example.app; use jp\nilay\enum\Enum; class Height extends Enum { #[Enum] public static function HIGH(): Height { return new static(); } #[Enum] public static function MEDIUM(): Height { return new static(); } #[Enum] public static function LOW(): Height { return new static(); } }
Extra attributes.
<?php // "High" var_dump(Height::HIGH()->getName()); // "H" var_dump(Height::HIGH()->getAbbr());
namespace com.example.app; use jp\nilay\enum\Enum; class Height extends Enum { protected string $name; protected string $abbr; public function __construct(string $name, string $abbr) { parent::__construct(); $this->name = $name; $this->abbr = $abbr; } public function getName(): string { return $this->name; } public function getAbbr(): string { return $this->abbr; } #[Enum] public static function HIGH(): Height { return new static("High", "H"); } #[Enum] public static function MEDIUM(): Height { return new static("Medium", "M"); } #[Enum] public static function LOW(): Height { return new static("Low", "L"); } }