Jso*_*owa 1 php switch-statement php-8
为什么我在执行匹配表达式时遇到错误:
$number = '1';
$result = match($number) {
1 => 'one',
2 => 'two',
3, 4 => 'three or four',
};
echo $result;
Run Code Online (Sandbox Code Playgroud)
致命错误:未捕获 UnhandledMatchError:未处理的字符串类型匹配值
正如文档中所述,匹配表达式必须包含详尽的模式。
UnhandledMatchError
当没有任何匹配模式时,就会发生错误。第二件事是它match
是类型敏感的,因此它不会将值转换为相应的模式。如果传递 string '1'
,它不会转换为 int 1
。一种可能的解决方案是提供默认值或将值转换为正确的类型。
$result = match($number) {
1 => 'one',
2 => 'two',
3, 4 => 'three or four',
default => 'unknown',
};
Run Code Online (Sandbox Code Playgroud)
或者
$result = match((int)$number) {
1 => 'one',
2 => 'two',
3, 4 => 'three or four',
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10785 次 |
最近记录: |