php - “致命错误:未捕获的 UnhandledMatchError:未处理的字符串类型的匹配值”
问题描述
执行匹配表达式时出现错误:
$number = '1';
$result = match($number) {
1 => 'one',
2 => 'two',
3, 4 => 'three or four',
};
echo $result;
致命错误:未捕获的 UnhandledMatchError:未处理的字符串类型的匹配值
解决方案
如文档中所述,匹配表达式必须包含详尽的模式。
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',
};
推荐阅读
- c++ - VS2013 C++ 自定义构建工具不起作用
- adsense - 我在我的网站上显示广告时遇到错误。使用 opencart 3 构建网站
- bash - 如何从 ~/.bashrc 中删除错误的链接?
- javascript - 如何在同一个事件监听器上隐藏和显示元素
- xcode - Mac OSX 10.11,配置:错误:C 编译器无法创建可执行文件
- c# - 并发字典内存效率
- session - 登录时 Cookie 无法正常工作
- java - Java 的 Stream.collect() 可以返回 null 吗?
- sql - SQL 我的查询什么也不返回
- javascript - Traying 用 AJAX 和 PHP 替换 JSON 中的数据