难道就不能使用“使用”吗? PHP 中的关键字在闭包上下文中带有匿名函数?
我正在尝试执行以下 PHP 代码:
$path_hierarchy = // function that returns an array
return array_reduce(
$terms,
function($val1, $val2) use ($path_hierarchy) {
return $val1 || in_array($val2, $path_hierarchy);
}
);
...但我收到以下 PHP 错误:
PHP 解析错误:语法错误,意外的 ')',期望 '{'
所以,我切换到以下语法:
$path_hierarchy = // function that returns an array
$callback = function($val1, $val2) use ($path_hierarchy) {
return $val1 || in_array($val2, $path_hierarchy);
};
return array_reduce(
$terms,
$callback
);
...这有效。我是否无法在匿名函数的上下文中使用 use
关键字作为另一个函数的参数?
I'm trying to execute the following PHP code:
$path_hierarchy = // function that returns an array
return array_reduce(
$terms,
function($val1, $val2) use ($path_hierarchy) {
return $val1 || in_array($val2, $path_hierarchy);
}
);
...but I'm getting the following PHP error:
PHP Parse error: syntax error, unexpected ')', expecting '{'
So, I switched to the following syntax:
$path_hierarchy = // function that returns an array
$callback = function($val1, $val2) use ($path_hierarchy) {
return $val1 || in_array($val2, $path_hierarchy);
};
return array_reduce(
$terms,
$callback
);
...and this worked. Am I not able to use the use
keyword in the context of an anonymous function as an argument to another function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

问题出在这里:第二个右括号。
The problem lies here: the second closing parenthesis.