diff --git a/_posts/03-02-01-Programming-Paradigms.md b/_posts/03-02-01-Programming-Paradigms.md index e7c5f52..1208b39 100644 --- a/_posts/03-02-01-Programming-Paradigms.md +++ b/_posts/03-02-01-Programming-Paradigms.md @@ -18,42 +18,36 @@ interfaces, inheritence, constructors, cloning, exceptions, and more. ### Functional Programming -PHP supports first-class functions. It is possible to define a new function and assign it to a variable name and built-in functions -can be referenced and called dynamically. Functions can be passed as arguments to other functions (Higher-order functions) and function -can return other functions. New anonymous functions (with support for closures) are present since PHP 5.3 (2009). +PHP supports first-class function, meaning that a function itself can be assigned to a variable, both user-defined and built-in. Those +functions referenced by a variable can be invoked dynamically. Functions can be passed as arguments to other functions (feature called +Higher-order functions) and function can return other functions. + +New anonymous functions (with support for closures) are present since PHP 5.3 (2009). + +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 (strategy, callback) used as a filter criteria on each array item. {% highlight php %} $min; }; } $input = array(1, 2, 3, 4, 5, 6); + +// Use array_filter on a input with a selected criteria function $output = array_filter($input, criteria_greater_than(3)); print_r($output); // items > 3 {% endhighlight %} +Each criteria function in the family accepts only elements greater than some minimum value. Single criteria returned by `criteria_greater_than` +is a closure whith `$min` argument closed by the value existing in the scope (given as 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. This can be used with some templating or input validation libraries, where anonymous function is defined to capture out-of-scope variables and access them later when the anonymous function is evaluated.