Type Matching in PHP – larry@garfieldtech.com

Type Matching in PHP

One of the nice features of Rust is the match keyword. match is similar to `switch`, but with two key differences:

  1. It requires an exhaustive match, that is, every possible value must be accounted for or a default must be provided.
  2. match is an expression, meaning you can assign the return value of one of its branches to a variable.

That makes match extremely useful for ensuring you handle all possibilities of an enumerated type, say, if using an Optional or 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