DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Aju Chacko
Aju Chacko

Posted on

ENUM IN PHP

Enum is the short form for an enumeration type, we use it to group named values. Enums are used instead of strings to denote the status of objects in an organised way. Unfortunately PHP doesn't have a native enum type. Although it offers a basic SPL implementation.

class Day extends SplEnum {    
    const MONDAY    = 1;
    const TUESDAY   = 2;
    const WEDNESDAY = 3;
    const THURSDAY  = 4;
    const FRIDAY    = 5;
    const SATURDAY  = 6;
    const SUNDAY    = 7;
}

echo new Day(Day::MONDAY);

try {
    new Day('UnknownDay');
} catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}

// RESULT
// 1
// Value not a const in enum Day

Better Version

Imagine we need to store Payment in a database, with its status represented as a string we could do it like this.

class Payment
{
    public function setStatus(string $status)
    {
        $this->status = $status;
    }
}

class PaymentStatus extends Enum
{
    const INITIATED = 'initiated';
    const PENDING   = 'pending';
    const COMPLETED = 'completed';
    const FAILED    = 'failed';
}

// ...

$payment->setStatus(PaymentStatus::COMPLETED);

This won't be doing any type checking so any string value can be passed to "setStatus()" method. There is a good package in php my Matthieu Napoli called myclabs/php-enum.

Solution

class Payment
{
    public function setStatus(PaymentStatus $status)
    {
        $this->status = $status;
    }
}

// ...

$payment->setStatus(PaymentStatus::COMPLETED());

Calling the PaymentStatus constant statuses as a method creates a new instance of PaymentStatus using php magic method __callStatic() with an attribute value of 'completed'. Now we can type check for PaymentStatus and ensure the input is one of the four things defined by the "enum".

Top comments (1)

Collapse
 
salimf profile image
SalimF

""Unfortunately PHP doesn't have a native enum type.""
PHP 8.1 ?

πŸŒ™ Dark Mode?!

Turn it on in Settings