(PHP 5 >= 5.6)
compose — Compose the given functions into a new one (a(b(c(x)))).
Closure compose( callable ...$fns )Create and return a new anonymous function that iterates over the function list (the given arguments) when executed.
Similar to sequence(), except the function list is executed in reverse — the last function is executed first.
compose(a, b, c) => a(b(c(x)))
The new function will chain the arguments between every function call and return the final result of the first argument.
Additional arguments can be passed to the composed function. They are applied to each function call but only the first argument is returned in the end.
x = a( b( c( x, y, z ), y, z ), y, z )
...$fns— One or more functions to compose.
Returns the newly created Closure object.
(PHP 5 >= 5.6)
sequence — Compose the given functions into a new one (c(b(a(x)))).
Closure sequence( callable ...$fns )Create and return a new anonymous function that iterates over the function list (the given arguments) when executed.
Similar to compose(), except the function list is executed in the order given.
sequence(a, b, c) => c(b(a(x)))
The new function will chain the arguments between every function call and return the final result of the first argument.
Additional arguments can be passed to the composed function. They are applied to each function call but only the first argument is returned in the end.
x = c( b( a( x, y, z ), y, z ), y, z )
...$fns— One or more functions to compose.
Returns the newly created Closure object.
Example #1 compose() example
$number = compose('round', 'floatval');
var_dump($number('72.5')); // float(73)Example #2 sequence() example
$length = function($text) {
return strlen($text);
};
$obscure = function($length) {
return str_repeat("*", $length);
};
$replace = sequence($length, $obscure);
var_dump($replace('password')); // "********"Example #3 sequence() example
$join = function($x) {
return implode(' ', $x);
};
$flip = function($a, $b) {
return [ $b, $a ];
};
$double = sequence($flip, $join);
var_dump($double('world', 'hello')); // "hello world"$ composer require mcaskill/php-compose-functions{
"repositories": [
{
"type": "git",
"url": "https://gist.github.com/***.git"
}
],
"require": {
"mcaskill/php-compose-functions": "dev-master"
}
}Why are you not using composer? Download Function.Compose-Sequence.php from the gist and save the file into your project path somewhere.
Based on "Function Composition" by Christopher Pitt and by "Composing Functions in JavaScript" Blake Embrey.