On Tue, 15 Dec 2020, 00:30 Andreas Leathley, <a.leath...@gmx.net> wrote:
> I checked in my vendor directory for currently used switch(true) usages, > there were 96 matches. It is often used when handling an unknown value > and needing to display or convert it, as there the structure of a switch > is easier to scan compared to other comparisons like ifs (at least it is > for me). Compared to match these switch statements are a lot uglier, > which shows that there are use cases for it even when you are forced to > use switch. > > This is a good example in my estimation, from the Symfony Console Dumper > class (taken from Symfony 5.2), when a value is converted into a string > representation: > > ```php > $this->handler = function ($var): string { > switch (true) { > case null === $var: > return 'null'; > case true === $var: > return 'true'; > case false === $var: > return 'false'; > case \is_string($var): > return '"'.$var.'"'; > default: > return rtrim(print_r($var, true)); > } > }; > ``` > > With match this becomes much more concise: > > ```php > $this->handler = function ($var): string { > return match { > null === $var => 'null', > true === $var => 'true', > false === $var => 'false', > \is_string($var) => '"'.$var.'"', > default => rtrim(print_r($var, true)), > }; > }; > ``` > > The same with ifs: > > ```php > $this->handler = function ($var): string { > if (null === $var) { > return 'null'; > } > if (true === $var) { > return 'true'; > } > if (false === $var) { > return 'false'; > } > if (\is_string($var)) { > return '"'.$var.'"'; > } > > return rtrim(print_r($var, true)); > }; > ``` > > The implied return type for match and the reduced amount of code to scan > makes match {} much better in my opinion, with ifs you always have to > make sure there isn't additional logic somewhere, and it makes it easy > to add more complex code "by accident" compared to match. match (true) > would be possible now, but the true makes the code a bit confusing, > while without the (true) it reads more like natural language ("match the > first possible expression in this list and return a corresponding value"). > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: https://www.php.net/unsub.php In OCaml they actually use `function` as a shorthand for lambda + match (on the implied first argument). `fun` is the lambda keyword (and also `let`). > >