PHP enumeration without SplEnum

PHP enumeration without SplEnum
PHP enumeration without SplEnum

PHP enumeration without SplEnum in simple way. Example for emulate and create enumeration objects in PHP without SplEnum. Simple PHP enumeration example.

If you want to safe some variable value unchanged and constant in project you can use constant. But if want to handle constant value in class, validate it and get it in required places. Here you found good example of PHP enumeration without SplEnum.

Main points for PHP enumeration

  1. PHP SPL Types the SplEnum class
  2. PHP enumeration without SplEnum example
  3. PHP enumeration class code
  4. How class work like PHP enumeration?

 

PHP SPL Types the SplEnum class

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.
You will found example and more detail at The SplEnum class in PHP manual.

PHP enumeration without SplEnum example

If you don’t want to use SplEnum process. Here is simple way to achieve same process.

PHP enumeration class code

Create file DaysOfWeekEnum.php

<?php
abstract class DaysOfWeek
{
    const SUNDAY = 'Sunday';
    const MONDAY = 'Monday';
    const TUESDAY = 'Tuesday';
    const WEDNESDAY = 'Wednesday';
    const THURSDAY = 'Thursday';
    const FRIDAY = 'Friday';
    const SATURDAY = 'Saturday';

    private static $days = [
        self::SUNDAY => 0,
        self::MONDAY => 1,
        self::TUESDAY => 2,
        self::WEDNESDAY => 3,
        self::THURSDAY => 4,
        self::FRIDAY => 5,
        self::SATURDAY => 6,
    ];

    public static function isValidDay($value)
    {
        return array_key_exists($value, self::$days);
    }

    public static function getValueByKey($key)
    {
        return self::$days[$key];
    }

    public static function getKeyByValue($value)
    {
        return (array_flip(self::$days))[$value];
    }
}

Now use class in process.

<?php

DaysOfWeek::SUNDAY; //Sunday

DaysOfWeek::isValidDay('Funday'); //false
DaysOfWeek::isValidDay('Monday'); //true

DaysOfWeek::getValueByKey('Sunday'); // 0
DaysOfWeek::getKeyByValue(0); // Sunday
 

How class work like PHP enumeration?

Example class have private $days variable so it not access and not change by other code. Also class is type of abstract, so its object can’t be created. Value can only be access static way.

Hope you find above process helpful and like to use in development process.