How does the concept of higher-order functions in PHP, such as array_map() and array_filter(), relate to the ability to declare functions within methods?
Higher-order functions in PHP, such as array_map() and array_filter(), allow functions to be passed as arguments to other functions. This concept is related to the ability to declare functions within methods because it enables the creation of reusable and modular code. By declaring functions within methods, you can encapsulate logic specific to that method and pass it as a callback to higher-order functions for processing arrays.
class Example {
public function filterArray($array) {
$filteredArray = array_filter($array, function($value) {
return $value > 5;
});
return $filteredArray;
}
}
$example = new Example();
$array = [2, 6, 8, 4, 10];
$filteredArray = $example->filterArray($array);
print_r($filteredArray);