6

I have the below sample code:

<?php

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

$enumClass = '\Suit';

$hearts = $enumClass::from('H');

var_dump($hearts);

it produces output

enum(Suit::Hearts)

which is desired. However, is there a way to do this using some function calls and not dynamic $enumClass::from('H'); ? Such as get_enum($enumClass)::from('H') or like that?

2
  • I'm not sure what the difference would be if your example was possible - if you are defining the class name dynamically, whatever function call you use would be dynamic. Are you actually hoping that the get_enum($enumClass) would be useful in some other way? Commented Apr 10, 2022 at 20:58
  • Apart from code readability, I think that static analysis is one example, where get_enum could throw expected Exceptions Commented Apr 10, 2022 at 21:15

1 Answer 1

8

PHP enumerations are objects and can be determined by autoloading. So if your variable only contains the name of the enumeration, you can first check if the enumeration exists and then use BackedEnum::tryFrom() or BackedEnum::from() to get it.

<?php
declare(strict_types=1);
namespace Marcel\Enums;

enum Status: string
{
    case Active = 'active';
    case Retired = 'retired';
}


$fqcn = Status::class;
$enum = null;
$value = 'active';

if (enum_exists($fqcn)) {
    $enum = $fqcn::from($value);
}

There is no additional functionality to get the object first and then execute some method of the object. You can get the fully qualified classname by get_class() and check in a next step, if the class (enum) exists and as a last step call the BackedEnum::from() method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.