Enum 枚举
枚举基础
枚举是在类、类常量基础上的约束层, 目标是提供一种能力:定义包含可能值的封闭集合类型。
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
function do_stuff(Suit $s)
{
// ...
}
do_stuff(Suit::Spades);
?>
详情参阅枚举章节。
类型转换
将 enum 转换为 object 不会有变化。
将 enum 转换为 array,
纯粹枚举会创建单个 name
键的数组;
回退枚举创建带 name
和 value
键的数组。
其他类型转换都会导致错误。

User Contributed Notes 1 note
esdras-schonevald ¶
1 month 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
}
备份地址:http://www.lvesu.com/blog/php/language.types.enumerations.php