首页 > 解决方案 > “致命错误:未捕获的 UnhandledMatchError:未处理的字符串类型的匹配值”

问题描述

执行匹配表达式时出现错误:

$number = '1';

$result = match($number) {
    1 => 'one',
    2 => 'two',
    3, 4 => 'three or four',
};

echo $result;

致命错误:未捕获的 UnhandledMatchError:未处理的字符串类型的匹配值

标签: phpswitch-statementphp-8

解决方案


如文档中所述,匹配表达式必须包含详尽的模式。

UnhandledMatchError当没有任何匹配模式时会发生错误。第二件事是match类型敏感的,因此它不会将值转换为相应的模式。如果您传递 string '1',它不会强制转换为 int 1。一种可能的解决方案是提供默认值或将值转换为正确的类型。

$result = match($number) {
    1 => 'one',
    2 => 'two',
    3, 4 => 'three or four',
    default => 'unknown',
};

或者

$result = match((int)$number) {
    1 => 'one',
    2 => 'two',
    3, 4 => 'three or four',
};

推荐阅读