W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
(PHP 8)
match 表達式基于值的一致性進行分支計算。 match表達式和 switch 語句類似, 都有一個表達式主體,可以和多個可選項進行比較。 與 switch 不同點是,它會像三元表達式一樣求值。 與 switch 另一個不同點,它的比較是嚴格比較( ===)而不是松散比較(==)。 Match 表達式從 PHP 8.0.0 起可用。
示例 #1 match 表達式結構
<?php
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
?>
示例 #2 match 的基礎用法
<?php
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
?>
以上示例會輸出:
string(19) "This food is a cake"
注意: 不一定要使用 match 表達式的結果。
注意: match 表達式必須使用分號 ; 結尾。
match 表達式跟 switch 語句相似,但是有以下關鍵區(qū)別:
match 表達式和 switch 語句類似, 逐個檢測匹配分支。一開始不會執(zhí)行代碼。 只有在所有之前的條件不匹配主體表達式時,才會執(zhí)行剩下的條件表達式。 只會執(zhí)行返回的表達式所對應的匹配條件表達式。 舉例:
<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // 如果 foo() === $x,不會執(zhí)行 $this->bar()
$this->baz => beep(), // 只有 $x === $this->baz 時才會執(zhí)行 beep()
// 等等
};
?>
match 表達式分支可以通過逗號分隔,包含多個表達式。 這是一個邏輯 OR,當多個分支表達式右側相同時,就可以用這種縮寫。
<?php
$result = match ($x) {
// 匹配分支:
$a, $b, $c => 5,
// 等同于以下三個分支:
$a => 5,
$b => 5,
$c => 5,
};
?>
default 模式是個特殊的條件。 當之前的條件都不匹配時,會匹配到該模式。 For example:
<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>
注意: 多個 default 模式將會觸發(fā) E_FATAL_ERROR 錯誤。
match 表達式必須詳盡列出所有情況。 如果主體表達式不能被任意分支條件處理, 會拋出 UnhandledMatchError。
示例 #3 match 表達式存在未處理的示例
<?php
$condition = 5;
try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>
以上示例會輸出:
object(UnhandledMatchError)#1 (7) {
["message":protected]=>
string(33) "Unhandled match value of type int"
["string":"Error":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(9) "/in/ICgGK"
["line":protected]=>
int(6)
["trace":"Error":private]=>
array(0) {
}
["previous":"Error":private]=>
NULL
}
可以使用 match 表達式將 true 作為主項表達式來處理非一致性條件的情況。
示例 #4 針對整數(shù)范圍,使用寬泛的表達式匹配分支
<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
?>
以上示例會輸出:
string(11) "young adult"
示例 #5 針對字符串內容,使用寬泛的表達式匹配分支
<?php
$text = 'Bienvenue chez nous';
$result = match (true) {
str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en',
str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr',
// ...
};
var_dump($result);
?>
以上示例會輸出:
string(2) "fr"
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: