Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jdp
Created March 26, 2012 00:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jdp/2201912 to your computer and use it in GitHub Desktop.
Save jdp/2201912 to your computer and use it in GitHub Desktop.
Partial function application with PHP
<?php
function foo($a, $b) {
echo "a: {$a} b: {$b}\n";
}
$foo_caller = new PartialCallable('foo', array('A'));
$foo_caller('B');
$foo_caller = partial_function('foo', 'A');
$foo_caller('B');
<?php
class PartialCallable {
function __construct($callable, $args) {
$this->callable = $callable;
$this->args = $args;
}
function __invoke() {
call_user_func_array($this->callable, array_merge($this->args, func_get_args()));
}
}
<?php
function partial_function() {
$applied_args = func_get_args();
return function() use($applied_args) {
return call_user_func_array('call_user_func', array_merge($applied_args, func_get_args()));
};
}
@xeoncross
Copy link

@neoascetic
Copy link

function partial($func, ...$args) {
    return function (...$margs) use ($func, $args) {
        return $func(...array_merge($args, $margs));
    };
}

@qwhex
Copy link

qwhex commented Jun 24, 2018

function partial($func, ...$args) {
    return function (...$newArgs) use ($func, $args) {
        return $func(...array_merge($args, $newArgs));
    };
}

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