- URL: https://www.laruence.com/en/2020/07/13/6033.html
- Please include attribution when republishing.
PHP 8 alpha2 is out, and it recently introduced a new keyword: match. Its role is somewhat similar to switch.
I'm usually indifferent to syntactic sugar, but I find this one rather interesting — and "match" is a nice-looking word. So what does it do?
In the past we often used switch for value-conversion work, like:
switch ($input) {
case "true":
$result = 1;
break;
case "false":
$result = 0;
break;
case "null":
$result = NULL;
break;
}
(Yes, some of you will say: who writes it like that, why not just use an array for the conversion? Come on, this is an example — arrays only give you string and integer keys; what if the key needs to be some other expression, or you want multiple keys mapping to one value, right?)
Now with the match keyword, it becomes something like:
$result = match($input) {
"true" => 1,
"false" => 0,
"null" => NULL,
};
Unlike switch, match directly returns a value, so you can assign it straight to $result.
And just as switch lets several cases share one block, match lets several conditions share one arm, for example:
$result = match($input) {
"true", "on" => 1,
"false", "off" => 0,
"null", "empty", "NaN" => NULL,
};
One important difference from switch: with switch we often ran into this eerie problem:
$input = "2 person";
switch ($input) {
case 2:
echo "bad";
break;
}
You'd find "bad" actually gets printed, because switch uses loose comparison (==). match doesn't have this problem — it uses strict comparison (===), requiring both value and type to be exactly equal.
Also, when the input satisfies none of the conditions in a match, it throws an UnhandledMatchError exception:
$input = "false";
$result = match($input) {
"true" => 1,
};
You get:
Fatal error: Uncaught UnhandledMatchError: Unhandled match value of type string
So you never have to worry that an incomplete set of match conditions will cause unpredictable errors.
One more thing to note: match is a keyword, which means from PHP 8 onward it cannot appear in namespace or class names. If your project has a class named match:
class Match {}
you'll get a syntax error starting with PHP 8. Method names, of course, may still use it.
For details, see the RFC: Match Expression
That's all.
Be First to Comment