PHP 8 :: Match Expression

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:

// Before
switch ($this->lexer->lookahead['type']) {
    case Lexer::T_SELECT:
        $statement = $this->SelectStatement();
        break;

    case Lexer::T_UPDATE:
        $statement = $this->UpdateStatement();
        break;

    case Lexer::T_DELETE:
        $statement = $this->DeleteStatement();
        break;

    default:
        $this->syntaxError('SELECT, UPDATE or DELETE');
        break;
}

// After
$statement = match ($this->lexer->lookahead['type']) {
    Lexer::T_SELECT => $this->SelectStatement(),
    Lexer::T_UPDATE => $this->UpdateStatement(),
    Lexer::T_DELETE => $this->DeleteStatement(),
    default => $this->syntaxError('SELECT, UPDATE or DELETE'),
};

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:

echo match ($x) {
    1, 2 => 'Same for 1 and 2',
    3, 4 => 'Same for 3 and 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*