Longhorn PHP 2023 - Call for Papers

Statik Sayılama Yöntemleri

Sayılamaların statik yöntemleri de olabilir. Statik yöntemlerin sayılamalar üzerinde kullanımının birincil amacı kurucu oluşturmaktır. Örnek:

<?php
enum Boyut
{
case
Küçük;
case
Normal;
case
Büyük;
public static function
uzunluğaGöre(int $cm): static
{
return
match(true) {
$cm < 50 => static::Küçük,
$cm < 100 => static::Normal,
default => static::
Büyük,
};
}
}
?>

Statik yöntemler public, private veya protected olabilirse de kalıtıma izin verilmediğinden uygulamada private ve protected eşdeğerdir.

add a note

User Contributed Notes 2 notes

up
33
niloofarfs
1 year 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');
    }
}

?>
up
0
Aaron Saray
6 months ago
Need to retrieve all the names and values immediately from a backed enum (for something like a select box) and you don't want to loop over `Enum::cases()`?  Try this:

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

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

Suit::forSelect();
?>

Put `forSelect()` in a trait and use it in any enum you have that needs this functionality.
To Top