微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于PHP8中match新语句的骚操作

PHP8新语法:match [更骚的匿名函数操作]

PHP8 新出的一个语法很好用,就是 match 语句。match 语句跟原来的 switch 类似,不过比 switch 更加的严格和方便

原来的 switch 语句代码如下:

function getStr( $strType ){
    switch( $strType ){
        case 1:
            $str = 'one';
            break;
        case 2:
            $str = 'two';
            break;
        default :
            $str = 'error';
    }
    return $str;
}
//当输入数值 1 和 字符 '1' 不会进行类型判断
echo getStr(1); //one
echo getStr('1'); //one
echo getStr(2); //two
echo getStr('2'); //two

换成 match 语句后:

function getStr( $strType ){
    return match( $strType ){
        1 => 'number one',
        '1' => 'string one',
        default => 'error',
    };
}
//可以看出输入数值 1 跟字符 `1` 返回的值是不同的
echo getStr(1); //number one
echo getStr('1'); //string one

骚操作

function getStr( $strType ){
    return match( $strType ){
        1 => (function(){
            return 'number one';
        })(),
        '1' => (function(){
            return 'string one';
        })(),
        default => 'error',
    };
}
//虽然这种代码风格也能行的通,但是总感觉哪里怪怪的
echo getStr(1); //number one
echo getStr('1'); //string one

总结:PHP8 新出的语法 match 相比原来的 switch 语法更加的方便和严格

推荐学习:《PHP8教程

原文地址:https://www.jb51.cc/php/2916521.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐