match
(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 語句相似,但是有以下關鍵區別:
-
match比較分支值,使用了嚴格比較 (===), 而 switch 語句使用了鬆散比較。 -
match表達式會返回一個值。 -
match的分支不會像switch語句一樣, 落空時執行下個 case。 -
match表達式必須徹底列舉所有情況。
match 表達式和 switch 語句類似,
逐個檢測匹配分支。一開始不會執行程式碼。
只有在所有之前的條件不匹配主體表達式時,才會執行剩下的條件表達式。
只會執行返回的表達式所對應的匹配條件表達式。
舉例:
<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // 如果 foo() === $x,不會執行 $this->bar()
$this->baz => beep(), // 只有 $x === $this->baz 時才會執行 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 模式將會觸發
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 表達式處理非一致性檢查
可以使用 match 表達式將 true
作為主項表達式來處理非一致性條件的情況。
示例 #4 針對整數範圍,使用寬泛的表達式匹配分支
<?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"