Last active
August 2, 2018 14:03
-
-
Save alastairparagas/67d0070111bd0e7abd172f6e66c2bbf0 to your computer and use it in GitHub Desktop.
Functional Programming in PHP
This file contains hidden or 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 | |
| // Accumulator gets passed around for reuse - function as a value | |
| $accumulator = function ( | |
| string $accumulated_string, | |
| string $mapped_list_element | |
| ) { | |
| return $accumulated_string . $mapped_list_element . "\n"; | |
| }; | |
| // Notice how array_map, array_filter and array_reduce | |
| // accept functions as parameters - they are higher order functions | |
| $mapped_array = array_reduce( | |
| array_map( | |
| function (int $list_element): string { | |
| return "A list element: " . $list_element; | |
| }, | |
| [1, 2, 3, 4] | |
| ), | |
| $accumulator, | |
| "" | |
| ); | |
| echo "Mapped Array: \n"; | |
| echo $mapped_array; | |
| $filtered_array = array_reduce( | |
| array_filter( | |
| [1, 2, 3, 4], | |
| function (int $list_element): bool { | |
| return $list_element > 2; | |
| } | |
| ), | |
| $accumulator, | |
| "" | |
| ); | |
| echo "Filtered Array: \n"; | |
| echo $filtered_array; | |
| // Closures "enclose" over their surrounding state | |
| // The $closure_incrementer function here returns a function | |
| // making it a higher order function. | |
| echo "Closure Incrementer: \n"; | |
| $closure_incrementer = function () { | |
| $internal_variable = 0; | |
| return function () use (&$internal_variable) { | |
| return $internal_variable += 1; | |
| }; | |
| }; | |
| $instance = $closure_incrementer(); | |
| echo $instance() . " is equal to 1\n"; | |
| echo $instance() . " is equal to 2\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment