Type Matching in PHP
One of the nice features of Rust is the
match is similar to `switch`, but with two key differences:
- It requires an exhaustive match, that is, every possible value must be accounted for or a default must be provided.
matchis an expression, meaning you can assign the return value of one of its branches to a variable.
match extremely useful for ensuring you handle all possibilities of an enumerated type, say, if using an
Either for error handling. Which… is something I’ve been experimenting with in PHP.
It’s hard to make a PHP equivalent of
match that forces an exhaustive match, as PHP lacks enumerated types. However, emulating an expression match turns out to be pretty easy in PHP 7.4, and kind of pretty, too.
2 February 2020 – 1:46pm