Home > database >  Variably typecasting strings to Enums in PHP
Variably typecasting strings to Enums in PHP

Time:10-19

Suppose I've got two Backed Enums:

enum Colors: string
{
    case Blue = "blue";
    case Red = "red";
}

enum Fruits: string
{
    case Apple = "apple";
    case Pear = "pear";
}

In my actual Yii2 implementation, I'd like to typecast variable object attributes to attribute type. In the database I store values as strings like "blue" and "apple" which I'd like to cast to enums. In the variable initialization of my custom so called 'Yii2 Behavior', I pass multiple parameters along like [color => Colors::class, fruit => Fruit::class], telling the behavior which Enum to parse certain attributes to. At that point the Behavior doesn't know anything of the actual values yet.

In the 'Behavior', a function ends up with $value and $type, where for example $value === "blue" and $type === "Namespace\Colors" (which is the result of Colors::class). I'd like this function to return enum Namespace\Colors::Blue.

I've tried

if($type instanceof \BackedEnum) {
    return $type::from($value);
}

which obviously fails as $type is just a string.

So I tried

if((new ($type)) instanceof \BackedEnum) {
    return $type::from($value);
}

which fails on Cannot instantiate enum 'Namespace\Colors'.

I'm stuck on this, does anyone have any idea how to solve this situation? What can I pass along or process differently to variably typecast a string to an Enum? Many

CodePudding user response:

From the code, because $type is a string, you cannot call a method on a string, you need some function like call_user_func to run it.

call_user_func([$type, 'from'], $value);
  • Related