Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Match expression of PHP8.0

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you the Match expression of PHP8.0 example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

In this article, we're going to talk about another newly introduced syntax, the match expression syntax, which is arguably one of the best features introduced by PHP 8, using a syntax similar to switch.

Basic function

$status = match ($request_method) {'post' = > $this- > handlePost (),' get', 'head' = > $this- > handleGet (), default = > throw new\ Exception (' Unsupported'),}

Compared with switch...case, the code should be a little more tedious to achieve the above functions:

Switch ($request_method) {case 'post': $status = $this- > handlePost (); break; case' get': case 'head': $status = $this- > handleGet (); break; default: throw new\ Exception (' Unsupported');}

Compared to switch, match returns the value directly without the need for intermediate variables (such as $status in the example above).

An expression can return a value

Each branch can be assigned to a variable.

$name = match (2) {1 = > 'One', 2 = >' Two',}

Instead of assigning the return value to another medium variable, the matching statement return value can be returned directly from the match expression.

Multiple conditions can be matched

An match expression may contain one or more matching conditions that behave like multiple cascading case keys switch in a block.

Match ($request_method) {'post' = > $this- > handlePost (),' get', 'head' = > $this- > handleGet (),}

Satisfying both the conditions of $request_method = = 'get' and $request_method = =' head' executes $this- > handleGet ().

Each branch can contain only one expression

Unlike blocks where switch can contain any number of expressions, a match statement can contain only one expression.

Match ($name) {'XXX' = > init (); doth ();}

The grammar above is wrong. = > there can be only one expression.

Implied break

Only one expression is allowed for each matching branch of an match expression, and there is no need for a break like a switch block.

Switch ('test') {case' test': $this- > doTest (); case 'send': $this- > sendmsg ();}

A common mistake in switch...caser is to forget the break statement, which takes the process straight to the next branch. In the switch block above, the lack of a break; statement prevents the code $this- > doTest () from executing properly.

Match ('test') {' test' = > $this- > doTest (), 'send' = > $this- > sendmsg (),}

Match expressions do not need explicit break statements to work. It executes only one match branch and returns that value immediately.

Default branch

The match statement supports a default branch that works similar to default in a switch...case block. If no other conditions match, the default match branch is executed.

Match ('DEF') {' aaa' = >..., 'bbb' = >..., default = > echo' NO matching:'. $name,}; / / "NO matchin: DEFF"

Match expression must meet the condition

If switch does not match the case key, block silently performs the code stream. Match expression does not exist.

In an match expression, there must be conditions that match the expression or conditions to be processed by default. If there is no match, and to set the default branch, the match expression throws a\ UnhandledMatchError exception.

$value = 3; match ($value) {1 = > 'One', 2 = >' Two',}

The above code throws an error when executed:

Fatal error: Uncaught UnhandledMatchError in...

Match\ UnhandledMatchError if there is no match in the expression, the expression throws an exception.

\ UnhandledMatchError is a new exception class in PHP 8, which extends\ Error. A complete hierarchy of all PHP core exception classes.

This class can be easily extended:

Class UnhandledMatchError extends\ Error {}

Strict matching of non-mandatory types

One of the most important design choices in match expressions is its matching of unforced types.

Function read (mixed $key): string {return match ($key) {1 = > 'Integer 1','1' = > 'String 1', true = > 'Bool true', [] = >' Empty array', [1] = > 'Array [1],};} read (1); / / "Integer 1" read (' 1'); / / "String 1"

In a typical switch block, its case is loosely matched, that is, with = =. In the match expression, all matching branches are matched by strict comparison (= =).

In the above code snippet, each individual branch will match its value and type.

Match any expression

Match expressions allow a given value to match the expression.

Match ($httpst) {404 = > 'Page not found', Response::REDIRECT = >' Redirect', $client- > getCode () = > 'Client Error', $response- > getCode () = >' Response Error', default = > 'Unknown error'}

Expressions are evaluated in the order in which they are arranged.

The match expression will try to match $httpst in the following order:

1. $httpst = 4042. $httpst = Response::REDIRECT 3. $httpst = $client- > getCode () 4. $httpst = $response- > getCode () 5. Default

If a positive match is found, the other branches will not be attempted and will be returned directly.

Match VS switch

Backward compatibility impact

Match expressions are the new syntax in PHP 8. Code that uses match expressions will not work in older versions of PHP.

The above is all the content of the article "sample Analysis of Match expressions of PHP8.0". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report