30 seconds of PHP

  Back to Home

curry

functionadvanced

Curries a function to take arguments in multiple calls.

If the number of provided arguments ($args) is sufficient, call the passed function, $function. Otherwise, return a curried function that expects the rest of the arguments.

function curry($function)
{
  $accumulator = function ($arguments) use ($function, &$accumulator) {
    return function (...$args) use ($function, $arguments, $accumulator) {
      $arguments = array_merge($arguments, $args);
      $reflection = new ReflectionFunction($function);
      $totalArguments = $reflection->getNumberOfRequiredParameters();

      if ($totalArguments <= count($arguments)) {
        return $function(...$arguments);
      }

      return $accumulator($arguments);
    };
  };

  return $accumulator([]);
}