新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
關(guān)于PHP8中match新語句的騷操作
php8新語法:match [更騷的匿名函數(shù)操作]

PHP8 新出的一個(gè)語法很好用,就是 match 語句。match 語句跟原來的 switch 類似,不過比 switch 更加的嚴(yán)格和方便
原來的 switch 語句代碼如下:
function getStr( $strType ){
switch( $strType ){
case 1:
$str = 'one';
break;
case 2:
$str = 'two';
break;
default :
$str = 'error';
}
return $str;
}
//當(dāng)輸入數(shù)值 1 和 字符 '1' 不會(huì)進(jìn)行類型判斷
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',
};
}
//可以看出輸入數(shù)值 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',
};
}
//雖然這種代碼風(fēng)格也能行的通,但是總感覺哪里怪怪的
echo getStr(1); //number one
echo getStr('1'); //string one
總結(jié):PHP8 新出的語法 match 相比原來的 switch 語法更加的方便和嚴(yán)格
分享標(biāo)題:關(guān)于PHP8中match新語句的騷操作
路徑分享:http://www.fisionsoft.com.cn/article/cdoscjd.html


咨詢
建站咨詢
