April 29, 2024
Breaking News

Match Expression is Coming to PHP 8 – Laravel News

The Match Expression v2 RFC has passed and targets the stable release of PHP v8.0! The RFC still leaves room for future improvement (noted in the RFC), but for now we get single-line expressions that provide a clean, terse syntax for matching expressions.

Since match() {} is an expression, you can capture the value via assignment or return without having to assign to a local variable:

1// Before

2switch ($this->lexer->lookahead['type']) {

3 case Lexer::T_SELECT:

4 $statement = $this->SelectStatement();

5 break;

6 

7 case Lexer::T_UPDATE:

8 $statement = $this->UpdateStatement();

9 break;

10 

11 case Lexer::T_DELETE:

12 $statement = $this->DeleteStatement();

13 break;

14 

15 default:

16 $this->syntaxError('SELECT, UPDATE or DELETE');

17 break;

18}

19 

20// After

21$statement = match ($this->lexer->lookahead['type']) {

22 Lexer::T_SELECT => $this->SelectStatement(),

23 Lexer::T_UPDATE => $this->UpdateStatement(),

24 Lexer::T_DELETE => $this->DeleteStatement(),

25 default => $this->syntaxError('SELECT, UPDATE or DELETE'),

26};

As you can see above, the match expression means no accidental fall through when you forget a break as part of a switch case. A missing condition (and no default provided) results in a thrown UnhandledMatchError exception with the match expression.

Match also allows you to combine multiple matches into one with the comma:

1echo match ($x) {

2 1, 2 => 'Same for 1 and 2',

3 3, 4 => 'Same for 3 and 4',

4};

Cool, when can I start using match?

The PHP 8 GA (General Availability) release is on November 26, 2020, which means you can start using match expressions later this year! Be sure to check out the Match Expression v2 RFC for further details on this new syntax feature.