tleckie / enum
PHP Enum. One advantage over using class constants is to be able to use an enum as a parameter type
Fund package maintenance!
teodoroleckie
www.paypal.com/donate?business=ZHYA2MTGA4884¤cy_code=USD
Requires
- php: ^8
Requires (Dev)
- friendsofphp/php-cs-fixer: v3.0.0-beta.2
- infection/infection: ^0.21.5
- phpunit/phpunit: ^9.5
README
Enumerator in php
Installation
You can install the package via composer:
composer require tleckie/enum
Usage
Extends Enum class and create your own type.
<?php /** * Class Vehicle * * @method static Vehicle CAR() * @method static Vehicle MOTORCYCLE() * @method static Vehicle BIKE() * @method static Vehicle TRICYCLE() * * @author Teodoro Leckie Westberg <teodoroleckie@gmail.com> */ class Vehicle extends Enum { public const CAR = 1; public const MOTORCYCLE = 2; public const BIKE = 3; public const TRICYCLE = 4; } $vehicle = new Vehicle(3); // Dynamic static methods available $vehicle::CAR(); // new Vehicle(1) $vehicle::MOTORCYCLE(); // new Vehicle(2) $vehicle::BIKE(); // new Vehicle(3) $vehicle::TRICYCLE(); // new Vehicle(4) . . . Vehicle::CAR(); // new Vehicle(1) Vehicle::MOTORCYCLE(); // new Vehicle(2) Vehicle::BIKE(); // new Vehicle(3) Vehicle::TRICYCLE(); // new Vehicle(4)
public function edit(Vehicle $vehicle){ //... } $object->edit(Vehicle::CAR());
$vehicle = new Vehicle(3); $vehicle->getValue(); // int(3) $vehicle->getKey(); // "BIKE"
getValues():
$vehicle = new Vehicle(3); $vehicle->getValues(); // [1,2,3,4]
getKeys():
$vehicle = new Vehicle(3); $vehicle->getKeys(); //["CAR","MOTORCYCLE","BIKE","TRICYCLE"]
toArray():
$vehicle = new Vehicle(3); $vehicle->toArray(); //["CAR" => 1,"MOTORCYCLE" => 2,"BIKE" => 3,"TRICYCLE" => 4]
Cast string
(string) Vehicle::MOTORCYCLE(); // "2" (string) new Vehicle(3); // "3" (string) new Vehicle( Vehicle::TRICYCLE() );// "4" (string) new Vehicle( new Vehicle(1) ); // "1"