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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With