What is use
?
use
means to inherit variables or values from current scope. Parameter can be given from anywhere, but use
d variable can exist only under certain circumstances. So you might not be able to use closure outside a scope, where use
d variable is not set:
<?php
header('Content-Type: text/plain; charset=utf-8');
$fn = function($x)use($y){
var_dump($x, $y);
};
$fn(1);
?>
Shows:
Notice: Undefined variable: y in script.php on line 4
int(1)
NULL
However, you can use parametrized closure without such scope-dependecy:
<?php
header('Content-Type: text/plain; charset=utf-8');
$fn = function($x, $y = null){
var_dump($x, $y);
};
$fn(1);
?>
See related question: In PHP 5.3.0, what is the function "use" identifier?.
What's an advantage?
One of the main use cases of use
construct is using closures as a callback for other functions (methods). In this case you must follow fixed number of function parameters. So the only way to pass extra parameters (variables) to a callback is use
construct.
<?php
header('Content-Type: text/plain; charset=utf-8');
$notWannaSeeThere = 15;
$array = [ 1, 15, 5, 45 ];
$filter = function($value) use ($notWannaSeeThere){
return $value !== $notWannaSeeThere;
};
print_r(array_filter($array, $filter));
?>
Shows:
Array
(
[0] => 1
[2] => 5
[3] => 45
)
In this example, $filter
closure is used by array_filter()
and called with only one argument - array element value (and we "can not" force it to use additional arguments). Still, we can pass there additionl variables, which availible in parent scope.
Reference: anonymous functions
.
Inheriting variables from the parent scope is not the same as using
global variables.