Skip to content

Instantly share code, notes, and snippets.

@azerum
Last active May 15, 2022 19:06
Show Gist options
  • Select an option

  • Save azerum/361b11bc3c96103c5fc37e4984575f63 to your computer and use it in GitHub Desktop.

Select an option

Save azerum/361b11bc3c96103c5fc37e4984575f63 to your computer and use it in GitHub Desktop.
Functions for partial application in PHP
<?php
function bind(callable $f, ...$params)
{
return function () use ($f, $params) {
return call_user_func_array($f, $params);
};
}
function partial(callable $f, ...$params)
{
$params_needed = (new ReflectionFunction($f))->getNumberOfParameters();
return _partial_recursive($f, $params, $params_needed);
}
function _partial_recursive(callable $f, array $passed_params, int $params_needed)
{
if (count($passed_params) >= $params_needed) {
return call_user_func_array($f, $passed_params);
}
return function (...$params) use ($f, $passed_params, $params_needed) {
return _partial_recursive(
$f,
array_merge($passed_params, $params),
$params_needed
);
};
}
@azerum
Copy link
Author

azerum commented Jul 30, 2021

Do not modify $passed_params array, because after its modification in closure partial function becomes unusable (array is already modified and function holds reference to it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment