PHP – 8.0 Match Expression
In PHP 8.0
there is a new feature or I should say a new language construct (keyword) going to be introduced, which has been implemented depending on the following RFC.
This
RFC
proposes adding a newmatch
expression that is similar toswitch
but with safer semantics and the ability to return values.
Let’s see an example using switch
:
switch (1) {
case 0:
$result = 'Foo';
break;
case 1:
$result = 'Bar';
break;
case 2:
$result = 'Baz';
break;
}
echo $result; // Bar
The same thing could be achieved using the new match
expression using something like the following:
$result = match (1) {
0 => 'Foo',
1 => 'Bar',
2 => 'Baz',
};
echo $result; // Bar
It looks like almost same but there is a lot of improvements in the new match
expression. The one obvious difference is that, a match
expression returns a (matched) value, which you might already have noticed.
Also it doesn’t require an explicit break
but in switch
, each case
must use an explicit break
to break out of the switch
statement or the execution will continue into the next case
even if the condition is not met. The match
expression uses an implicit break
after every arm.
Also multiple conditions could be used using comma, for example:
echo match ($x) {
1, 2 => 'Same for 1 and 2',
3, 4 => 'Same for 3 and 4',
};
The match
expression throws an UnhandledMatchError
if the condition isn’t met for any of the arms. For example:
$result = match ($operator) {
BinaryOperator::ADD => $lhs + $rhs,
};
// Throws when $operator is BinaryOperator::SUBTRACT
Backward Incompatible Changes
Since, the match
was added as a keyword, which means it can’t be used in the following contexts anymore:
- namespaces
- class names
- function names
- global constants
Note that it will continue to work in method names and class constants.
Well, these are some examples of new match
expression and most of the examples were taken from the RFC page. There are more to learn about it so please visit the RFC page to explore it.
In my opinion, this is a very useful feature added to the PHP
which will allow to write less error prone code with less typing and also it’ll be more clean and readable.