PHP8 中引入了一个新的关键字:match,这个关键字的作用跟 switch 有点类似。

在以前我们可能会经常使用 switch 做值转换类的工作,类似:

$result = '';
switch ($input) {
    case "true":
        $result = 1;
    break;
    case "false":
        $result = 0;
    break;
    case "null":
        $result = NULL;
    break;
}

那么如果使用 match 关键字呢,可以变成类似:

$result = match($input) {
        "true" => 1,
        "false" => 0,
        "null" => NULL,
};

相比 switch, match 会直接返回值,可以直接赋值给 $result 了。

并且,类似switch的多个case一个block一样,match的多个条件也可以写在一起,比如:

$result = match($input) {
    "true", "on" => 1,
    "false", "off" => 0,
    "null", "empty", "NaN" => NULL,
};

需要注意的和 switch 不太一样的是,以前我们用 switch 可能会经常遇到这种诡异的问题:

$input = "2 person";
switch ($input) {
    case 2:
        echo "bad";
    break;
}

你会发现,bad 竟然被输出了,这是因为 switch 使用了宽松比较(==)。match 就不会有这个问题了, 它使用的是严格比较(===),就是值和类型都要完全相等。

还有就是,当 input 并不能被 match 中的所有条件满足的时候,match 会抛出一个UnhandledMatchError exception:

$input = "false";
$result = match($input) {
        "true" => 1,
};

会得到:

Fatal error: Uncaught UnhandledMatchError: Unhandled match value of type string

这样就不用担心万一 match 条件没写全导致了不可预知的错误。

另外还是要说明,match 是关键字,也就是从 PHP8 开始它不能出现在 namespace 或者类名中,如果你的项目中有用 match 作为类名的:

class Match {}

在 PHP8 开始将会得到语法错误了, 当然,方法名中还是可以用的。

本文转载自风雪之隅博客:https://www.laruence.com/2020/07/13/6033.html