BackedEnum::tryFrom

(PHP 8 >= 8.1.0)

BackedEnum::tryFromMaps a scalar to an enum instance or null

Descrizione

public static BackedEnum::tryFrom(int|string $value): ?static

The tryFrom() method translates a string or int into the corresponding Enum case, if any. If there is no matching case defined, it will return null.

Elenco dei parametri

value

The scalar value to map to an enum case.

Valori restituiti

A case instance of this enumeration, or null if not found.

Esempi

Example #1 Basic usage

The following example illustrates how enum cases are returned.

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

$h = Suit::tryFrom('H');

var_dump($h);

$b = Suit::tryFrom('B') ?? Suit::Spades;

var_dump($b);
?>

Il precedente esempio visualizzerà:

enum(Suit::Hearts)
enum(Suit::Spades)

Vedere anche:

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top