Created
March 26, 2012 00:44
-
-
Save jdp/2201912 to your computer and use it in GitHub Desktop.
Partial function application with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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())); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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())); | |
}; | |
} |
function partial($func, ...$args) {
return function (...$margs) use ($func, $args) {
return $func(...array_merge($args, $margs));
};
}
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
From the article: http://blog.justinpoliey.com/partial-function-application-in-php.html