Re: [RFC] Short-match

From: Date: Tue, 15 Dec 2020 19:37:25 +0000
Subject: Re: [RFC] Short-match
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-112518@lists.php.net to get a copy of this message
On 15.12.20 20:08, Sara Golemon wrote:
Or even better with existing syntax:
$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:
$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.

« previous php.internals (#112518) next »