【问题标题】:Trying to pass callback function with parameters as a function argument - getting "Unexpected callbackFunctionName, expecting '(' " error尝试将带有参数的回调函数作为函数参数传递 - 出现“意外的回调函数名称,期待 '('”错误
【发布时间】:2018-08-14 19:24:20
【问题描述】:

我正在尝试使用 this open source PHP class 并调用 setInterval() 函数。从链接的 github 页面:

/**
 * Just for simplifying the Timers::setInterval method
 *
 *
 * @param callable | string $func
 * @param float $milliseconds
 *
 * @return integer
 */
function setInterval ($func, $milliseconds)
{
    return Timers::setInterval($func, $milliseconds);
}

如您所见,它接受一个函数作为第一个参数,所以我尝试向它传递一个回调函数followed this SO answer for the syntax。这是我的代码:

declare(ticks=1) {
            setInterval(function callbackFunction() use $someArrayFromOuterScope {

                    runSomeOtherFunction();
                    //Do something

            }, $someArrayFromOuterScope[0]["time"]);
}

但我得到了错误:

解析错误:语法错误,意外的回调函数,期待'('

所以问题是我在这里做错了什么,我该如何纠正它?

【问题讨论】:

  • 匿名函数不应该有名字。这是你的语法错误。

标签: php callback anonymous-function declare callable-object


【解决方案1】:

试试这个...

    function setInterval ($func, $milliseconds)
    {
        return Timers::setInterval($func, $milliseconds);
    }
    declare(ticks=1) {
        setInterval(function($someArrayFromOuterScope) {

                runSomeOtherFunction();
                //Do something

        }, $someArrayFromOuterScope[0]["time"]);
    }

【讨论】:

  • “试试这个”并不是一个好的答案。你应该解释如何为什么这可以解决他们的问题。我推荐阅读,“How do I write a good answer?"
猜你喜欢
  • 2015-08-29
  • 1970-01-01
  • 2019-02-22
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多