diff --git a/_posts/03-02-01-Programming-Paradigms.md b/_posts/03-02-01-Programming-Paradigms.md index 4754ca0..692021f 100644 --- a/_posts/03-02-01-Programming-Paradigms.md +++ b/_posts/03-02-01-Programming-Paradigms.md @@ -5,8 +5,8 @@ isChild: true ## Programming Paradigms PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over -the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP -5.3 (2009), and traits in PHP 5.4 (2012). +the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 +(2009), and traits in PHP 5.4 (2012). ### Object-oriented Programming @@ -18,23 +18,22 @@ interfaces, inheritence, constructors, cloning, exceptions, and more. ### Functional Programming -PHP has had support for anonymous functions and closures since PHP 5.3: +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. -{% 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