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 o
.........................................................