CascadiaPHP 2024

BackedEnum::from

(PHP 8 >= 8.1.0)

BackedEnum::fromMaps a scalar to an enum instance

Descripción

public static BackedEnum::from(int|string $value): static

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

Parámetros

value

The scalar value to map to an enum case.

Valores devueltos

A case instance of this enumeration.

Ejemplos

Ejemplo #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::from('H');

var_dump($h);

$b = Suit::from('B');
?>

El resultado del ejemplo sería:

enum(Suit::Hearts)

Fatal error: Uncaught ValueError: "B" is not a valid backing value for enum "Suit" in /file.php:15

Ver también

add a note

User Contributed Notes 1 note

up
0
imefisto at gmail dot com
17 days ago
Note that the `from` method also can be called from a defined enum to get another value:

<?php
enum Foo: int {
case
A = 1;
case
B = 2;
}

$e1 = Foo::A;
$e2 = $e1->from(2);

echo
$e1->value . PHP_EOL;
echo
$e2->value . PHP_EOL;

// prints:
// 1
// 2
?>
To Top