I search for a simple solution to get the case of an enum by a string.
There are BackedEnums. For example:
<?php
enum Status: string
{
case OK = "OK";
case FAILED = "FAILED";
...
}
$status = Status::tryFrom("OK"); // or from("OK");
But I don't want to write the same word twice for getting that result. Is there a native way to get the case without having BackedEnums?
I want something like:
<?php
enum Status
{
case OK;
case FAILED;
...
}
$status = Status::get("OK"); //returns Status::OK;
Or do I need to write my own funcionality for that? For example:
enum Status
{
case OK;
case FAILED;
public static function get(string $name): null|Status
{
$name = strtoupper(trim($name));
if(empty($name))
return null;
foreach(Status::cases() as $status)
{
if($status->name == $name)
return $status;
}
return null;
}
}
Status::get("OK"); // -> Status::OK
Is there a better way to achieve the same?
My Answer:
php
class BackedEnum {
const CASE_ONE = 'case_one';
const CASE_TWO = 'case_two';
const CASE_THREE = 'case_three';
}
function getEnumCase($string) {
$reflectionClass = new ReflectionClass('BackedEnum');
$constants = $reflectionClass->getConstants();
foreach ($constants as $name => $value) {
if ($value === $string) {
return $name;
}
}
return null;
}
// Example usage
$case = getEnumCase('case_two');
echo $case; // Output: CASE_TWO
Rate this post
5 of 5 based on 4865 votesComments