PHP Velho Oeste 2024

Константы перечислений

В перечисления разрешено включать константы с общедоступной, закрытой или защищённой областью видимости, хотя на практике закрытые и защищённые константы эквивалентны, поскольку наследование не разрешено.

Константе перечисления разрешено ссылаться на вариант перечисления:

<?php

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

public const
Huge = self::Large;
}
?>
add a note add a note

User Contributed Notes 1 note

up
2
Hayley Watson
7 months 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