【发布时间】:2021-02-08 08:05:59
【问题描述】:
缺少参数的函数会引发ArgumentCountError 错误
ArgumentCountError: 函数的参数太少...
而未知的命名参数只会引发一般错误
错误:未知的命名参数...
我只想捕获这两个错误,到目前为止我有以下错误
function foo(int $bar, int $baz) {}
try {
foo(...$arr); // $arr is always an associative array
} catch (ArgumentCountError $error) {
// ...
} catch (Error $error) {
if (preg_match("/^Unknown named parameter/", $e->getMessage())) {
// ...
} else {
throw $error;
}
}
我有哪些替代方法? Unknown named parameter 不应该得到它自己的错误。
编辑:
对于UnknownNamedParameterError 的用法
try {
$dynamicFoo(...$args);
} catch (UnknownNamedParameterError $error) {
// if needed, a check to confirm the error happened in foo
if (($error->getTrace()[0]["function"] ?? null) === $dynamicFoo) {
// Hacky but whatever
}
}
【问题讨论】:
-
检查 $arr 是否为空。
标签: php error-handling arguments parameter-passing php-8