layout | title |
---|---|
page |
Functional Programming in PHP |
PHP supports first-class function, meaning that a function can be assigned to a variable. Both user defined and built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other functions (feature called Higher-order functions) and function can return other functions.
Recursion, a feature that allows a function to call itself is supported by the language, but most of the PHP code focus on iteration.
New anonymous functions (with support for closures) are present since PHP 5.3 (2009).
PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they can be used interchangeably with anonymous functions in almost all cases.
The most common usage of higher-order functions is when implementing a strategy pattern. Built-in array_filter
function asks both for the input array (data) and a function (a strategy or a callback) used as a filter function on
each array item.
{% highlight php %}
$min * * Returns a single filter out of a family of "greater than n" filters */ function criteria_greater_than($min) { return function($item) use ($min) { return $item > $min; }; } $input = array(1, 2, 3, 4, 5, 6); // Use array_filter on a input with a selected filter function $output = array_filter($input, criteria_greater_than(3)); print_r($output); // items > 3 {% endhighlight %} Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by `criteria_greater_than` is a closure whith `$min` argument closed by the value in the scope (given as an argument when `criteria_greater_than` is called). Early binding is used by default for importing `$min` variable into the created function. For true closures with late binding one should use a reference when importing. Imagine a templating or input validation libraries, where closure is defined to capture variables in scope and access them later when the anonymous function is evaluated. * [Read about Anonymous functions][anonymous-functions] * [More details in the Closures RFC][closures-rfc] * [Read about dynamically invoking functions with `call_user_func_array`][call-user-func-array] [anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php [call-user-func-array]: http://php.net/manual/en/function.call-user-func-array.php [closures-rfc]: https://wiki.php.net/rfc/closures