温馨提示  2024年 6月我们已经停止开发者板块文章内容更新,谢谢来访。存档数据
知识 2023-08-27 30 次阅读

关于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); //oneecho getstr('1'); //oneecho getstr(2); //twoecho getstr('2'); //two

换成 match 语句后

function getstr( $strtype ){ return match( $strtype ){ 1 => 'number one', '1' => 'string one', default => 'error', };}//可以看出输入数值 1 跟字符 `1` 返回的值是不同的echo getstr(1); //number oneecho 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 oneecho getstr('1'); //string one

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

推荐学习《php8教程》