难道就不能使用“使用”吗? PHP 中的关键字在闭包上下文中带有匿名函数?

发布于 12-22 06:44 字数 665 浏览 6 评论 0原文

我正在尝试执行以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

謌踐踏愛綪2024-12-29 06:44:54

返回$val1 || in_array($val2, $path_hierarchy))

问题出在这里:第二个右括号。

return $val1 || in_array($val2, $path_hierarchy))

The problem lies here: the second closing parenthesis.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文