Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Last active August 2, 2018 14:03
Show Gist options
  • Select an option

  • Save alastairparagas/67d0070111bd0e7abd172f6e66c2bbf0 to your computer and use it in GitHub Desktop.

Select an option

Save alastairparagas/67d0070111bd0e7abd172f6e66c2bbf0 to your computer and use it in GitHub Desktop.
Functional Programming in PHP
<?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