21

PHP8新特性之match表达式

 3 years ago
source link: https://www.laruence.com/2020/07/13/6033.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

这个我觉得还是有点意思,match这个词也挺好看,那么它是干啥的呢?

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

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

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

function converti($input) {
    return match($input) {
        "true" => 1,
        “false” => 0,
        “null” => NULL,
    };
}

相比switch, match会直接返回值,不再需要上面switch例子中的$result中间变量。

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

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

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

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

function convert($input) {
    return match($input) {
        "true" => 1,
    };
}
convert("false");

会得到:

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

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

详细的,可以参考RFC: Match Expression

以上。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK