PHP 8.4.0 RC4 available for testing

枚举常量

虽然 enum 可以包括 public、private、protected 的常量, 但由于它不支持继承,因此在实践中 private 和 protected 效果是相同的。

枚举常量可以引用枚举条目:

<?php

enum Size
{
case
Small;
case
Medium;
case
Large;

public const
Huge = self::Large;
}
?>
添加备注

用户贡献的备注 1 note

up
8
Hayley Watson
1 year ago
Just to clarify, enum constants *can* contain cases, but they don't *have* to; other constant values are legitimate - including cases of other Enumerations.

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

public const
Card = Size::Large; // A case from a different enum
}

enum
Size
{
case
Small;
case
Medium;
case
Large;

public const
Scale = 297/210; // A float
}

echo
Suit::Diamonds::Card::Scale; // Getting the constant Scale from the constant Card in a Suit.
?>
To Top