簡體   English   中英

PHP 8 匹配表達式與 PHP 7 開關盒有什么區別?

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

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 (8.0) {
  case '8.0':
    $result = "Oh no!";
    break;
  case 8.0:
    $result = "This is what I expected";
    break;
}
echo $result;
//> Oh no!
  1. 哪一個提供更好的性能?
  2. 匹配和切換的用例。

主要區別:

  • match 是一個表達式,而 switch 是語句
  • match 使用嚴格比較,而 switch 使用松散
  • match 只評估一個值,而 switch 可能評估更多(取決於 break 語句)
  • match 只允許單行表達式,而 switch 允許語句塊

如果您想了解更多,匹配表達式已經在 PHP 文檔中找到了它的頁面: https://www.php.net/manual/en/control-structures.match.ZE1BFD762321E409CEE4AC0B6E84193CZZAC0B6E84196

匹配表達式基於值的身份檢查分支評估。 與 switch 語句類似,匹配表達式具有與多個備選方案進行比較的主題表達式。 與 switch 不同,它的計算結果很像三元表達式。 與 switch 不同,比較是身份檢查 (===) 而不是弱相等檢查 (==)。 匹配表達式自 PHP 8.0.0 起可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM