PHP 8.1 起有了原生枚举(enum),转成字符串分三种情况,用错会直接 Fatal Error,先把结论摆出来:
| 你想拿到的 | 写法 | 适用 |
|---|---|---|
| 枚举名称(case 名字) | $s->name |
纯枚举 & backing 枚举都行 |
| 枚举值(背后那个值) | $s->value |
仅 Backed Enum (: string / : int) |
echo / 拼接时自动转 |
实现 Stringable 或自己写 toString() |
两种枚举都需要手动加 |
⚠️ 原生枚举默认没有
__toString(),echo $status;会直接抛:
Error: Object of class Status could not be converted to string
一、Backed Enum(最常用,推荐)
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Trash = 'trash';
}
$s = Status::Published;
echo $s->name; // "Published" ← case 名
echo $s->value; // "published" ← 背后存的值(入库、出 API 用这个)
- 存数据库 / 返 JSON / 写日志 → 用
->value - 反射、动态调用
Status::from()→ 用->name(或->value,见下)
反向转回来:
Status::from('published'); // Status::Published,找不到抛 ValueError
Status::tryFrom('foo'); // null,不抛异常(推荐用于用户输入)
二、Pure Enum(没有 backing 值)
enum Color
{
case Red;
case Green;
}
$c = Color::Red;
echo $c->name; // "Red" ✅ 只有 name,没有 value
echo $c->value; // ❌ Error: Undefined property
想让它"像字符串一样用",只能自己加方法:
enum Color
{
case Red;
case Green;
public function label(): string
{
return match($this) {
self::Red => '红色',
self::Green => '绿色',
};
}
}
echo Color::Red->label(); // 红色
三、让 echo $enum / 字符串拼接不报错
枚举不能 写 __toString()?------ 其实可以(PHP 8.1 允许 enum 实现接口、写普通方法,包括魔术方法),只是默认没给你:
enum Status: string implements Stringable
{
case Draft = 'draft';
case Published = 'published';
public function __toString(): string
{
return $this->value; // 或 $this->name,看你想暴露哪个
}
}
echo "当前状态:" . Status::Draft; // 当前状态:draft ✅
💡 实现
Stringable是"声明式"好习惯,PHP 会在需要字符串的地方自动调用。
四、JSON 序列化
json_encode($status) 对 Backed Enum 默认只输出 value?
------ 错,默认输出的是 {"name":"Draft","value":"draft"} 吗?也不是。
实际行为:
json_encode(Status::Draft); // "\"draft\"" ← 只有 value(PHP 8.1+ 对 BackedEnum 的实现)
json_encode(Color::Red); // {} ← Pure Enum 是空对象 ⚠️
所以:
- Backed Enum 出 JSON 很省心,前端拿到的就是字符串
'draft' - Pure Enum 千万别直接 json_encode ,会得到
{}。要么改成 Backed Enum,要么在 DTO 里手动->name
五、实战:一条龙工具 trait
项目里我一般会塞个 trait,省得每个枚举都重写:
trait EnumToString
{
public function __toString(): string
{
// Backed Enum 有 value,Pure Enum 退回 name
return $this->value ?? $this->name;
}
/** @return array<string,string> 下拉框用 */
public static function options(): array
{
$out = [];
foreach (self::cases() as $c) {
$out[$c->value ?? $c->name] = $c->name;
}
return $out;
}
}
enum Status: string
{
use EnumToString;
case Draft = 'draft';
case Published = 'published';
}
echo Status::Draft; // draft
var_dump(Status::options());
// ['draft' => 'Draft', 'published' => 'Published']
六、和数据库 / ORM 打交道
Laravel(Eloquent 8.1+ 原生支持)
protected $casts = [
'status' => Status::class, // 入库自动 ->value,取出自动 BackedEnum
];
Doctrine
#[Column(type: 'string', enumType: Status::class)]
public Status $status;
两者存的就是 value,读取时自动变回 enum,不用你手写转换。
七、常见坑速查
| 现象 | 原因 | 解决 |
|---|---|---|
Object of class X could not be converted to string |
没实现 __toString |
implements Stringable + 写 __toString |
Undefined property: $value |
Pure Enum 没有 value | 用 ->name 或改成 Backed Enum |
ValueError: "xxx" is not a valid backing value |
from() 碰到脏数据 |
用 tryFrom() |
json_encode 出 {} |
Pure Enum | 换 Backed Enum 或手动转 |
in_array($enum, ['draft']) 永远 false |
对象是对象,字符串是字符串 | in_array($enum->value, [...]) 或 in_array($enum, [Status::Draft, ...], true) |
switch 里写 'draft' 匹配不上 |
同上 | match($enum) { Status::Draft => ... } |
一句话总结
- 拿字符串:Backed 用
->value,Pure 用->name- 要
echo/ 拼接:给枚举加__toString()并implements Stringable- 用户输入转枚举:
tryFrom(),别用from()- 纯枚举要进 JSON / 入库:趁早改成 Backed Enum ,别和
{}较劲