Movatterモバイル変換


[0]ホーム

URL:


PHP 8.5.0 Alpha 2 available for testing
    Resources »
    « Objects

    Enumerations

    (PHP 8 >= 8.1.0)

    Basic Enumerations

    Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type.

    <?php
    enumSuit
    {
    case
    Hearts;
    case
    Diamonds;
    case
    Clubs;
    case
    Spades;
    }

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

    do_stuff(Suit::Spades);
    ?>

    For a full discussion, see theEnumerations chapter.

    Casting

    If anenum is converted to anobject, it is not modified. If anenum is converted to anarray, an array with a singlename key (for Pure enums) or an array with bothname andvalue keys (for Backed enums) is created. All other cast types will result in an error.

    Found A Problem?

    Learn How To Improve This PageSubmit a Pull RequestReport a Bug
    add a note

    User Contributed Notes1 note

    esdras-schonevald
    3 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^
    */

    enumMyExceptionCase{
    case
    InvalidMethod;
    case
    InvalidProperty;
    case
    Timeout;
    }

    class
    MyExceptionextendsException{
    function
    __construct(privateMyExceptionCase $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
    }
    add a note
    To Top
    and to navigate •Enter to select •Esc to close
    PressEnter without selection to search using Google

    [8]ページ先頭

    ©2009-2025 Movatter.jp