PHP8 new syntax: match [more exciting anonymous function operation]
PHP8 has a new syntax that is very useful, which is the match statement. The match statement is similar to the original switch, but more strict and convenient than switch.
The original switch statement code is as follows:
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
After replacing it with the match statement:
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
Sao Operation
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
Summary: PHP8’s new syntax match is more convenient and strict than the original switch syntax
Recommended study: "PHP8 Tutorial"
The above is the detailed content of About the cool operation of the new match statement in PHP8. For more information, please follow other related articles on the PHP Chinese website!