PHP 8.5.0 Beta 3 available for testing

UnitEnum::cases

(PHP 8 >= 8.1.0)

UnitEnum::casesBir sayılamadan kılıf listesi oluşturur

Açıklama

public static UnitEnum::cases(): array

Bu yöntem, bir sayılamadaki tüm kılıfları bildirildikleri sıraya göre içeren bir dizi döndürür.

Bağımsız Değişkenler

Bu işlevin bağımsız değişkeni yoktur.

Dönen Değerler

Sayılamadaki tüm kılıfları bildirildikleri sıraya göre içeren bir dizi döner.

Örnekler

Örnek 1 - Temel kullanım örneği

Bu örnekte sayılama kılıflarının nasıl döndürüleceği gösterilmiştir.

<?php
enum Deste
{
case
Kupalar;
case
Karolar;
case
Sinekler;
case
Maçalar;
}
var_dump(Deste::cases());
?>

Yukarıdaki örneğin çıktısı:

array(4) {
    [0]=>
    enum(Deste::Kupalar)
    [1]=>
    enum(Deste::Karolar)
    [2]=>
    enum(Deste::Sinekler)
    [3]=>
    enum(Deste::Maçalar)
}
add a note

User Contributed Notes 2 notes

up
60
avishkasenanayake at hotmail dot com
2 years ago
If anyone is here wondering how to get all the names from the enum cases and map them into an array, it can be done like this:

array_column(CampaignPeriods::cases(), 'name');

Likewise, have the 2nd argument as 'value' to get the enum's values.

Happy coding, web artisan :)
up
0
miken32 at example dot com
7 days ago
The Enum documentation says, "if a Backed Enum is serialized to JSON, it will be represented by its scalar value only, in the appropriate type."

This means you can easily get a backed Enum's values for use in a JSON document using only the BackedEnum::cases() method:

<?php
enum Suits: string {
case
Hearts = 'Heart';
case
Diamonds = 'Diamond';
case
Clubs = 'Spade';
case
Spades = 'Club';
}
echo
json_encode(Suits::cases());
?>

Results in this output:

["Heart","Diamond","Spade","Club"]
To Top