PHP 8.1.28 Released!

常量表达式的枚举值

由于用 enum 自身的常量表示条目,它们可当作静态值,用于绝大多数常量表达式: 属性默认值、变量默认值、参数默认值、全局和类常量。 他们不能用于其他 enum 枚举值,但通常的常量可以引用枚举条目。

然而,因为不能保证结果值绝对不变,也不能避免调用方法时带来副作用, 所以枚举里类似 ArrayAccess 这样的隐式魔术方法调用无法用于静态定义和常量定义。 常量表达式还是不能使用函数调用、方法调用、属性访问。

<?php

// 这是完全合法的 Enum 定义
enum Direction implements ArrayAccess
{
case
Up;
case
Down;

public function
offsetExists($offset): bool
{
return
false;
}

public function
offsetGet($offset): mixed
{
return
null;
}

public function
offsetSet($offset, $value): void
{
throw new
Exception();
}

public function
offsetUnset($offset): void
{
throw new
Exception();
}
}

class
Foo
{
// 可以这样写。
const DOWN = Direction::Down;

// 由于它是不确定的,所以不能这么写。
const UP = Direction::Up['short'];
// Fatal error: Cannot use [] on enums in constant expression
}

// 由于它不是一个常量表达式,所以是完全合法的
$x = Direction::Up['short'];
var_dump("\$x is " . var_export($x, true));

$foo = new Foo();
?>
add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top