tleckie/enum

PHP Enum. One advantage over using class constants is to be able to use an enum as a parameter type

1.0.2 2021-05-01 11:21 UTC

This package is auto-updated.

Last update: 2022-06-13 10:58:15 UTC


README

Latest Version on Packagist Scrutinizer Code Quality Build Status Total Downloads Code Intelligence Status

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"