Home > Backend Development > PHP8 > body text

About the cool operation of the new match statement in PHP8

藏色散人
Release: 2023-02-17 12:28:01
forward
2773 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:janrs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!