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'); //twoAfter 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 oneSao 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 oneSummary: 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.





