Question

This example taken from phptherightway's functional programming page.

<?php
/**
 * Creates an anonymous filter function accepting items > $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

What is the purpose of having return function() ?

I just wrote this and it does the same thing.

array_filter($input, function($input) use ($min) {
    return $input > $min;
}); // items > 3

Even if I appoint this callback to a function, the secondary function seems unnecessary.

Did I overlook something or does it have a different purpose?

Was it helpful?

Solution

It's absolutely necessary for criteria_greater_than to return the value you want to return. Eg. for a function to return the value 5:

function get_5() {
    return 5;
}

You use it like $var = get_5();, but if you were setting it to a constant you would just do $var = 5; or call_my_function(5). Notice you need to use return in order to return anything in a function. Now consider this function:

function get_fx($x)
{
    return function () use ($x)
           {
               return $x;
           };
}

$v5 = get_fx(5);
$v6 = get_fx(6);

What are $v5 and $v6?.. Well they are functions, because thats what they returned. In fact $v5() == get_5() is true, but $6() == get_5() is false, because get_fx return different functions (closures) dependent on the arguments passed.

If you were to skip the first return you wouldn't get anything from the first function.. eg. $v5 and $v6 wouldn't have anything assigned. If you skipped the second return in the returned function they wouldn't return anything when called, ie. $v5() wouldn't return 5 and $v6() wouldn't return 6.

OTHER TIPS

Second param of array_filter is callback. You can specify it inside array_filter as anonymous function or specify name of the function. Inside of anonymous function you do the filtering, that's why return used. The second one return is to use anonymous function as a callback at array_filter it returns the reference on this function.

Second function allows you to pass not only callback to array_filter but callback and filtration context ($min) at once. It is convinient way to reuse code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top