略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 枚举静态方法

2024-04-29

枚举静态方法

枚举也能有静态方法。 在枚举中静态方法主要用于取代构造器,如:

<?php
enum Size
{
    case 
Small;
    case 
Medium;
    case 
Large;

    public static function 
fromLength(int $cm): static
    {
        return 
match(true) {
            
$cm 50 => static::Small,
            
$cm 100 => static::Medium,
            default => static::
Large,
        };
    }
}
?>

仅管 enum 可以包括 public、private、protected 的静态方法, 但由于它不支持继承,因此在实践中 private 和 protected 效果是相同的。

add a noteadd a note

User Contributed Notes 1 note

up
9
niloofarfs
3 months ago
To get all scalar equivalents values of Backed Enum as an array you could define a method in your Enum:

<?php

enum Suit
: string
{
    case
Hearts = 'H';
    case
Diamonds = 'D';
    case
Clubs = 'C';
    case
Spades = 'S';

    public static function
values(): array
    {
       return
array_column(self::cases(), 'value');
    }
}

?>

官方地址:https://www.php.net/manual/en/language.enumerations.static-methods.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3