I've been learning web development using php and I'm a little bit confused about the anonymous functions. 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. 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?
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.
The $a
and $b
values come from inside the usort()
function. Its code calls the provided function with 2 parameters. Your parameters don't need to be named $a
and $b
, they can be named whatever you like.
Your question is not actually about anonymous functions but about passing 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.
Well, the answer is very simple. usort
expects you to provide callable that will take 2 arguments and it calls it internally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.