Search code examples
phpcallbackanonymous-functiondeclarecallable-object

Trying to pass callback function with parameters as a function argument - getting "Unexpected callbackFunctionName, expecting '(' " error


I am trying to use this open source PHP class and call the setInterval() function. From the linked github page:

/**
 * 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);
}

As you can see, it takes a function as the first argument, so I tried to pass it a callback function, and followed this SO answer for the syntax. Here is my code:

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

                    runSomeOtherFunction();
                    //Do something

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

But I am getting the error:

Parse error: syntax error, unexpected callbackFunction, expecting '('

So the question is that what am I doing wrong here, and how can I correct it?


Solution

  • Try this...

        function setInterval ($func, $milliseconds)
        {
            return Timers::setInterval($func, $milliseconds);
        }
        declare(ticks=1) {
            setInterval(function($someArrayFromOuterScope) {
    
                    runSomeOtherFunction();
                    //Do something
    
            }, $someArrayFromOuterScope[0]["time"]);
        }