简体   繁体   English

理解PHP的匿名函数

[英]Understanding anonymous functions PHP

I've been learning web development using php and I'm a little bit confused about the anonymous functions. 我一直在使用php学习web开发,我对匿名函数有点困惑。 Specifically concerning the pass of parameters and how they work inside a funcion like that. 特别是关于参数的传递以及它们如何在这样的函数内工作。 For example, in the code 例如,在代码中

$array = array("really long string here, boy", "this", "middling length", "larger");
usort($array, function($a, $b) {
return strlen($a) - strlen($b);
});
print_r($array);

I don't really get how the parameters $a and $b are used. 我真的不知道如何使用参数$a$b I think they're taken for comparison in order sort the array for where is defined how the function should use them and take them from? 我认为它们是为了比较而对数组进行排序,以确定函数应该如何使用它们并将它们从中取出?
In a code like the next one 在下一个代码中

$mult = function($x)
{
 return $x * 5;
};
echo $mult(2);

I know the parameter is passed directly to the function and used to return the result of the multiplication. 我知道参数直接传递给函数并用于返回乘法的结果。
In this post the example of 在这篇文章中的例子

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);

where is the variable $val taken from? 变量$val取自哪里?

I know maybe this is not as complicated as it seems but I'm really confused about the use of the parameters on this kind of functions 我知道也许这并不像看起来那么复杂,但我真的很困惑在这种功能上使用参数

usort($array, function($a, $b) {
    return strlen($a) - strlen($b);
});

Let's take this example. 我们来看看这个例子吧。 When you pass a function to usort() , PHP internally calls it with 2 elements from your array to see which is bigger/smaller. 当您将函数传递给usort() ,PHP会在内部使用数组中的2个元素调用它,以查看哪个更大/更小。

The $a and $b values come from inside the usort() function. $a$b值来自内部 usort()函数。 Its code calls the provided function with 2 parameters. 它的代码用2个参数调用提供的函数。 Your parameters don't need to be named $a and $b , they can be named whatever you like. 您的参数不需要命名为$a$b ,它们可以根据您的喜好命名。

Your question is not actually about anonymous functions but about passing calllables. 你的问题实际上并不是关于匿名函数,而是关于传递calllables。

Let's take the first of you examples under consideration 让我们考虑你们中的第一个例子

usort($array, function($a, $b) {
return strlen($a) - strlen($b);
});

Let's refactor it a little bit by replacing anonymous function with named function. 让我们通过用命名函数替换匿名函数来重构它。

function compareAB($a, $b) {
return strlen($a) - strlen($b);
}

usort($array, 'comapreAB');

As you see you still can ask how $a and $b are passed. 如你所见,你仍然可以问$a$b是如何通过的。

Well, the answer is very simple. 嗯,答案很简单。 usort expects you to provide callable that will take 2 arguments and it calls it internally. usort希望你提供带有2个参数的callable,并在内部调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM