(PHP 8)
match 表達式基于值的一致性進(jìn)行分支計算。
match表達式和 switch 語(yǔ)句類(lèi)似,
都有一個(gè)表達式主體,可以和多個(gè)可選項進(jìn)行比較。
與 switch 不同點(diǎn)是,它會(huì )像三元表達式一樣求值。
與 switch 另一個(gè)不同點(diǎn),它的比較是嚴格比較(
===)而不是松散比較(==)。
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);
?>
以上例程會(huì )輸出:
string(19) "This food is a cake"
注意: 不一定要使用
match表達式的結果。
注意:
match表達式必須使用分號;結尾。
match 表達式跟 switch 語(yǔ)句相似,但是有以下關(guān)鍵區別:
match 比較分支值,使用了嚴格比較 (===),
而 switch 語(yǔ)句使用了松散比較。
match 表達式會(huì )返回一個(gè)值。
match 的分支不會(huì )像 switch 語(yǔ)句一樣,
落空時(shí)執行下個(gè) case。
match 表達式必須徹底列舉所有情況。
match 表達式和 switch 語(yǔ)句類(lèi)似,
逐個(gè)檢測匹配分支。一開(kāi)始不會(huì )執行代碼。
只有在所有之前的條件不匹配主體表達式時(shí),才會(huì )執行剩下的條件表達式。
只會(huì )執行返回的表達式所對應的匹配條件表達式。
舉例:
<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // 如果 foo() === $x,不會(huì )執行 $this->bar()
$this->baz => beep(), // 只有 $x === $this->baz 時(shí)才會(huì )執行 beep()
// 等等
};
?>
match 表達式分支可以通過(guò)逗號分隔,包含多個(gè)表達式。
這是一個(gè)邏輯 OR,當多個(gè)分支表達式右側相同時(shí),就可以用這種縮寫(xiě)。
<?php
$result = match ($x) {
// 匹配分支:
$a, $b, $c => 5,
// 等同于以下三個(gè)分支:
$a => 5,
$b => 5,
$c => 5,
};
?>
default 模式是個(gè)特殊的條件。
當之前的條件都不匹配時(shí),會(huì )匹配到該模式。
For example:
<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>
注意: 多個(gè) default 模式將會(huì )觸發(fā)
E_FATAL_ERROR錯誤。
match 表達式必須詳盡列出所有情況。
如果主體表達式不能被任意分支條件處理,
會(huì )拋出 UnhandledMatchError。
示例 #3 match 表達式存在未處理的示例
<?php
$condition = 5;
try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>
以上例程會(huì )輸出:
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
作為主項表達式來(lái)處理非一致性條件的情況。
示例 #4 針對整數范圍,使用寬泛的表達式匹配分支
<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
?>
以上例程會(huì )輸出:
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);
?>
以上例程會(huì )輸出:
string(2) "fr"