
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教程》
以上就是关于PHP8中match新语句的骚 *** 作的详细内容,
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)