简体   繁体   English

PHP 8 匹配表达式与 PHP 7 开关盒有什么区别?

[英]What are the difference between PHP 8 Match expression vs PHP 7 switch case?

PHP 8 Match expression code PHP 8 匹配表达式代码

echo match (8.0) {
    '8.0' => "Oh no!",
     8.0 => "This is what I expected",
};
//> This is what I expected

PHP 7 switch code PHP 7 开关代码

switch (8.0) {
  case '8.0':
    $result = "Oh no!";
    break;
  case 8.0:
    $result = "This is what I expected";
    break;
}
echo $result;
//> Oh no!
  1. Which one give better performance?哪一个提供更好的性能?
  2. Use case of match and switch.匹配和切换的用例。

Main differences:主要区别:

  • match is an expression, while switch is statement match 是一个表达式,而 switch 是语句
  • match uses strict comparison, while switch uses loose match 使用严格比较,而 switch 使用松散
  • match evaluates only one value, while switch may evaluate more (depending on break statement) match 只评估一个值,而 switch 可能评估更多(取决于 break 语句)
  • match allows only single-line expression, while switch allows block of statements match 只允许单行表达式,而 switch 允许语句块

Match expression has got already its page in the PHP documentation if you want to know more: https://www.php.net/manual/en/control-structures.match.php如果您想了解更多,匹配表达式已经在 PHP 文档中找到了它的页面: https://www.php.net/manual/en/control-structures.match.ZE1BFD762321E409CEE4AC0B6E84193CZZAC0B6E84196

The match expression branches evaluation based on an identity check of a value.匹配表达式基于值的身份检查分支评估。 Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives.与 switch 语句类似,匹配表达式具有与多个备选方案进行比较的主题表达式。 Unlike switch, it will evaluate to a value much like ternary expressions.与 switch 不同,它的计算结果很像三元表达式。 Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==).与 switch 不同,比较是身份检查 (===) 而不是弱相等检查 (==)。 Match expressions are available as of PHP 8.0.0.匹配表达式自 PHP 8.0.0 起可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM