PHP.mk документација

СТАТИЧКИ МЕТОДИ НАENUMЕРАЦИЈА

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

language.enumerations.static-methods.php PHP.net прокси Преводот е вчитан
Оригинал на PHP.net
Патека language.enumerations.static-methods.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + преведен приказ Кодовите, табелите и белешките остануваат читливи во истиот тек.
СТАТИЧКИ МЕТОДИ НАENUMЕРАЦИЈА

Референца за `language.enumerations.static-methods.php` со подобрена типографија и навигација.

language.enumerations.static-methods.php

СТАТИЧКИ МЕТОДИ НАENUMЕРАЦИЈА

Енумерациите исто така може да имаат статични методи. Употребата за статични методи на самата емнумерација е првенствено за алтернативни конструктори. На пр.:

<?php

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

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

Статичните методи може да бидат јавни, приватни или заштитени, иако во пракса приватните и заштитените се еквивалентни бидејќи наследувањето не е дозволено.

Белешки од корисници 5 белешки

niloofarfs
пред 4 години
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');
    }
}

?>
joe502357217 на qq точка com
пред 2 години
You simply need to use the following code as a replacement for the example provided by Aaron Saray.
This piece of code is more concise.

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

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

var_dump(Suit::forSelect());
?>
Улф
пред 2 години
Note, that enums are internally declared as final and thus, cannot extend each other (though, they are allowed to extend other classes).

That also means, that the "Size::fromLength()" method from this page's example redundantly uses "static::" (because there's no late static binding required), and could easily use "self::" or "Size::" instead.

See: https://php.watch/versions/8.1/enums#enum-inheritance
lokashafeek7755 на gmail точка com
пред 2 години
If you want to supplement the key-value pairs with additional descriptions for each enum value in the forSelect method, you can modify the array structure to include an associative array for each enum value. Here's an example:

<?php 

enum Gender:int
{
    case Male = 1;
    case Female = 2;

    public static function forSelect(): array
    {
        return [
            self::Male->value => [
                'label' => 'Male',
                'description' => 'This is the Male gender',
            ],
            self::Female->value => [
                'label' => 'Female',
                'description' => 'This is the Female gender',
            ],
        ];
    }

}
?>

In this updated example, each enum value is represented as an associative array with two keys: 'label' and 'description'. You can customize the label and description for each enum value accordingly.

Please note that to access the label and description for a specific enum value, you would need to use the corresponding array keys. For example, to get the label for the Male gender, you can use self::forSelect()[self::Male->value]['label'].
Арон Сарај
3 години пред
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.