PHP 8.4.24 Released!

Enumerazioni

(PHP 8 >= 8.1.0)

Enumerazioni di base

Le enumerazioni sono un livello restrittivo sopra le classi e le costanti di classe, pensato per fornire un modo di definire un insieme chiuso di valori possibili per un tipo.

<?php
enum Suit
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

function do_stuff(Suit $s)
{
    // ...
}

do_stuff(Suit::Spades);
?>

Per una trattazione completa, vedere il capitolo sulle Enumerazioni.

Casting

Se un enum viene convertito in un object, non viene modificato. Se un enum viene convertito in un array, viene creato un array con una singola chiave name (per le enum Pure) o un array con entrambe le chiavi name e value (per le enum Backed). Tutti gli altri tipi di cast produrranno un errore.

add a note

User Contributed Notes 1 note

up
50
esdras-schonevald
4 years ago
https://gist.github.com/esdras-schonevald/71a6730e6191c5e9c053e2f65b839eec

<?php

declare(strict_types=1);

/**
 * This is a sample
 * How to use Enum to create a custom exception cases
 * PHP 8.1^
 */

enum MyExceptionCase {
    case InvalidMethod;
    case InvalidProperty;
    case Timeout;
}

class MyException extends Exception {
    function __construct(private MyExceptionCase $case){
        match($case){
            MyExceptionCase::InvalidMethod      =>    parent::__construct("Bad Request - Invalid Method", 400),
            MyExceptionCase::InvalidProperty    =>    parent::__construct("Bad Request - Invalid Property", 400),
            MyExceptionCase::Timeout            =>    parent::__construct("Bad Request - Timeout", 400)
        };
    }
}

// Testing my custom exception class
try {
    throw new MyException(MyExceptionCase::InvalidMethod);
} catch (MyException $myE) {
    echo $myE->getMessage();  // Bad Request - Invalid Method
}
To Top