klamius/php-enum

A PHP library providing a way to work with enumeration

1.0.1 2018-08-23 20:22 UTC

This package is not auto-updated.

Last update: 2024-06-09 04:06:35 UTC


README

Build Status Code Coverage Scrutinizer Code Quality Total Downloads Latest Stable Version

Installation

by using composer

composer require klamius/php-enum

Philosophie

This library give an easier way to emulate and create enumeration objects natively in PHP and be replacement to SplEnum which is not integrated directly to PHP.

In our daily usage we deal with many enums (all domain entity states, months, genders, etc. ) and we get into dilemma, should it be Class member, constants or Interface constants and so on. and then we treat it as a scalar value which most of time can't be validated or type hinted.

So using an enum instead of constants provides the following advantages:

  • type hint: function setState(OrderStateEnum $state) {

Declaration

use Klamius\Enum\Enum;

/**
 * GenderEnum enum
 */
class Gender extends Enum
{
    const MALE = 'male';
    const FEMALE = 'female';
}

Usage

class User
{
    /**
     * @var Gender
     */
    private $gender;
    
    function setGender(Gender $gender)
    {
        $this->gender = $gender;
    }
}

$gender = new Gender(Gender::MALE);
$user->setGender($gender);

//or
echo $gender;