此示例来自Phptherightway的功能编程页面。

<?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

拥有的目的是什么 return function() ?

我只是写了这篇文章,它做同样的事情。

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

即使我将此回调任命为函数,辅助功能似乎也不需要。

我忽略了某些东西还是有不同的目的?

有帮助吗?

解决方案

绝对有必要 criteria_greater_than 返回要返回的值。例如。为了返回值5:

function get_5() {
    return 5;
}

你喜欢它 $var = get_5();, ,但是,如果您将其设置为一个常数,那么您只会这样做 $var = 5; 或者 call_my_function(5). 。注意您需要使用 return 为了返回函数中的任何内容。现在考虑此功能:

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

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

什么是 $v5$v6?..它们是功能,因为那是他们返回的。实际上 $v5() == get_5() 是真的,但是$ 6()== get_5()是错误的,因为 get_fx 返回根据传递的参数返回不同的功能(关闭)。

如果您要跳过第一个 return 您不会从第一个功能中获得任何东西。 $ v5和$ v6不会分配任何东西。如果您跳过了第二个 return 在返回的功能中,他们不会在被调用时返回任何内容,即。 $v5() 不会返回5和 $v6() 不会返回6。

其他提示

第二个参数 array_filtercallback. 。您可以在里面指定它 array_filter 作为 anonymous function 或指定功能的名称。代替 anonymous function 您进行过滤,这就是为什么 return 用过的。第二个返回是将匿名函数用作回调 array_filter 它返回此功能的参考。

第二个功能使您不仅可以将回调传递给array_filter,还可以一次回调和过滤上下文($ min)。这是重复使用代码的有说服力的方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top