How to declare and use enum in PHP

4 Answers

0 votes
enum Status {
    case Pending;
    case Approved;
    case Decline;
}

$status = Status::Pending;
echo $status->name . "\n"; 


if ($status === Status::Approved) {
    echo "The status is approved!";
}

foreach (Status::cases() as $case) {
    echo $case->name . PHP_EOL; 
}



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';
}

$status = Status::Pending;
echo $status->name . "\n"; 


if ($status === Status::Approved) {
    echo "The status is approved!";
}

foreach (Status::cases() as $case) {
    echo $case->name . PHP_EOL; 
}



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';
}

enum Status {
    case Pending;
    case Approved;
    case Decline;

    public function isFinal(): bool {
        return $this === self::Approved || $this === self::Decline;
    }
}

$status = Status::Approved;
echo $status->isFinal() ? 'Yes' : 'No'; 



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';

    public static function fromValue(string $value): ?self {
        foreach (self::cases() as $case) {
            if ($case->value === $value) {
                return $case;
            }
        }
        return null;
    }
}

$status = Status::fromValue('approved');
echo $status->name; 



/*
run:

Approved

*/

 



answered Jun 9, 2025 by avibootz

Related questions

1 answer 80 views
3 answers 367 views
1 answer 177 views
177 views asked Jan 19, 2017 by avibootz
2 answers 215 views
1 answer 159 views
1 answer 179 views
...