Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting with enumerations?

I've read here about enumarations and their "implementation"

PHP and Enumerations

point is, why use enums, when not for type hinting?

but this implementation does not allow use for type hinting. Because the enum entries are all strings.

is there a way I can say

function($a) {

}

$a must be 'foo', 'bar' or 'baz'

in PHP?

I use phpstorm/intellij so if there is another way to do that, that would be fine too. E.g. say in the doc but with autocompletion magic from phpstorm, or maybe compile errors.

like image 649
Toskan Avatar asked Mar 12 '23 09:03

Toskan


1 Answers

Starting in PHP 8.1, you'll be able to use actual enumerations.

enum A {
    case FOO = 'foo';
    case BAR = 'bar';
    case BAZ = 'baz';
}

Then in your function a(), you'd type-hint for the enumeration A.

function a(A $a) {
    echo $a->value;
}

Now a($a) would only accept:

a(A::FOO);
a(A::BAR);
a(A::BAZ);

or even:

a(A::from('bar'));

but any input that's not a valid case would fail with a ValueError exception.

like image 100
yivi Avatar answered Mar 16 '23 03:03

yivi