rybosome
rybosome

Reputation: 5136

Is it not possible to use the "use" keyword in PHP with an anonymous function in a closure context?

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?

Upvotes: 0

Views: 178

Answers (1)

TimWolla
TimWolla

Reputation: 32701

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

The problem lies here: the second closing parenthesis.

Upvotes: 5

Related Questions