PHP 8.0: Match Expressions

栏目: IT技术 · 发布时间: 1个月前

来源: php.watch

内容简介:Match expression syntax is one of the nicest features in PHP 8 that improves theFunctionality from theThe return value of the expression used in each "arm" (similar to each

本文转载自:https://php.watch/versions/8.0/match-expression,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有。

Match expression syntax is one of the nicest features in PHP 8 that improves the switch syntax in multiple ways.

$status = match($request_method) {
    'post' => $this->handlePost(),
    'get', 'head' =>  $this->handleGet(),
    default => throw new \Exception('Unsupported'),
};

Functionality from the match expression above, compared to a switch block:

- switch ($request_method) {
+ $status = match($request_method) {
-   case 'post':
-       $status = $this->handlePost();
-       break;
+   'post' => $this->handlePost(),
-   case 'get':
-   case 'head':
-       $status = $this->handleGet();
-       break;
+   'get', 'head' =>  $this->handleGet(),
-   default:
-       throw new \Exception('Unsupported'); 
+   default => throw new \Exception('Unsupported'),
- }
+ };

match expressions can return a value

The return value of the expression used in each "arm" (similar to each case in switch blocks) is can be assigned to a variable.

$name = match(2) {
    1 => 'One',
    2 => 'Two',
};

echo $name; // "Two"

It is not necessary to assign the return value to anything, the return value of the matched arm will be returned from the match expression.

Multiple matching conditions allowed

It is possible for a match expression to contain one or more matching conditions, and they will behave similar to multiple cascading case keys in a switch block.

match($request_method) {
    'post' => $this->handlePost(),
    'get', 'head' =>  $this->handleGet(),
};

$request_method === 'get' and $request_method === 'head' both conditions will be handled with $this->handleGet() .

Each matching case must only contain one expression

Unlike switch blocks that can contain any number of expressions, a match arm can only contain only one expression.

match($name) {
    'foo' => 
        initFoo();
        processFoo();
};

Syntax above is not allowed . Each arm must contain only a single expression.

Implicit break

Each matched "arm" of a match expression only allows a single expression, and it will not fall-through, as it does in a switch block.

switch ('test') {
    case 'test':
        $this->sendTestAlert();
    case 'send':
        $this->sendNuclearAlert();
}

It is easy to overlook the missing break call in each of the switch case , which allows the code to fall-through to the next case. In the switch block above, missing break; statement makes the code fall-through and execute $this->sendNuclearAlert() as well, although it is unlikely the outcome you expect.

match ('test') {
    'test' => $this->sendTestAlert(),
    'send' => $this->sendNuclearAlert(),
};

match expressions work without explicit break statements. It only executes one matching arm, and immediately returns the value, making it imply a break call right after the expression the matched arm executes.

default case

match statement supports a default arm that will work similar to the default case in switch blocks.

A default arm will catch all expressions if none of the other conditions matched.

match ('Qux') {
    'foo' => ...,
    'bar' => ...,
    default => echo 'Unknown: ' . $name,
};

// "Unknown: Qux"

match expression MUST match a condition

switch blocks silently proceeds the code flow if there are no matching case keys. match expressions do not.

In a match expression, there must be condition that matches the expression, or a default case to handle it. If there are no matches, match expression throws an \UnhandledMatchError exception.

$value = 3;
match($value) {
    1 => 'One',
    2 => 'Two',
};

match expression above throws error:

Fatal error: Uncaught UnhandledMatchError in ...

UnhandledMatchError exception

match expressions throw an \UnhandledMatchError exception if there are no matches in within the expression.

\UnhandledMatchError is a new exception class in PHP 8, and it extends \Error . For a full hierarchy of all PHP core exception classes, including the ones added in PHP 8, see Hierarchy of PHP exceptions

This class can be easily poly-filled:

class UnhandledMatchError extends \Error {}

Strict matches without type coercion

One of the most important design choices in match expression is that it matches without type coercion.

function read(mixed $key): string {
    return match ($key) {
        1 => 'Integer 1',
        '1' => 'String 1',
        true => 'Bool true',
        [] => 'Empty array',
        [1] => 'Array [1]',
    };
}

read(1); // "Integer 1"
read('1'); // "String 1"
read(true); // "Bool true"

In a typical switch block, its cases are matched loosely, i.e with == . In match expressions, all matching arms are matched with strict comparison ( === ), leaving possible bugs in switch blocks out.

In the snippet above, each individual arm will be matched for the value and type.

Match against arbitrary expressions

match expression allows a given value to be matched against an expression.

match($foo){
    404 => 'Page not found',
    Response::REDIRECT => 'Redirect',
    $client->getCode() => 'Client Error',
    $response->getCode() => 'Response Error',
    default => 'Unknown error'
};

The expressions will be evaluated in the order they are laid out.

match expression will try to match $foo against in this order:

$foo === 404
$foo === Response::REDIRECT
$foo === $client->getCode()
$foo === $response->getCode()
default

If it finds a positive match, the rest of the code will not be evaluated.

match vs switch

switch match
Requires PHP ^8.0 No Yes
No Yes
default condition support Yes Yes
Multiple conditions in single arm Yes Yes
Multiple expressions in code block Yes No
No Yes
Falls-through without break Yes No
Throws an exception on no matches No Yes
Match against arbitrary expressions Yes Yes
Strict type-safe comparison No Yes

Backwards compatibility impact

match expressions are a new syntax in PHP 8. Code that uses match expressions will not work in older PHP versions.

The \UnhandledMatchError exception class can be.

Trying to run code that uses this expression will fail with a parse error in older PHP versions:

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in ... on line ...

以上所述就是小编给大家介绍的《PHP 8.0: Match Expressions》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

关注码农网公众号

关注我们,获取更多IT资讯^_^


为你推荐:

相关软件推荐:

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming PHP

Programming PHP

Rasmus Lerdorf、Kevin Tatroe、Peter MacIntyre / O'Reilly Media / 2006-5-5 / USD 39.99

Programming PHP, 2nd Edition, is the authoritative guide to PHP 5 and is filled with the unique knowledge of the creator of PHP (Rasmus Lerdorf) and other PHP experts. When it comes to creating websit......一起来看看 《Programming PHP》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具