On 15.12.20 20:08, Sara Golemon wrote:
Or even better with existing syntax:
```php
$this->handler = match($var) {
   null, true, false => json_encode($var),
   default => \is_string($var) ? "\"$var\"" : \rtrim(\print_r($var, true)),
};

I appreciate that this is a specific counter-example to your example, but
you picked the bad example. :p

Sure, for this specific example - there are of course longer real-life
examples (sometimes even nested ones), often using instanceof, is_array,
is_callable and similar constructs, but they seem a bit too much for a
discussion. If you add slightly more logic then it might be better:

```php
$this->handler = function ($var): string {
     return match {
         null === $var => 'null',
         true === $var => 'true',
         false === $var => 'false',
         is_string($var) => '"'.$var.'"',
         is_callable($var) => 'callable',
         is_object($var) => get_class($var),
         default => rtrim(print_r($var, true)),
     };
};
```

I guess that would be an advantage of these current switch(true) (and
possibly future match {}) statements: it is easy to add additional
matches that do not impact the others.

I do like Nikitas idea to make it a TypeError for non-bool matches.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to