use is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the closure.
bar = function () {
// can't access $foo in here
echo $foo; // undefined variable
};
$baz = function () use ($foo) {
// $foo is made available in here by use()
echo $foo; // 42
}
For example:
$array = array('foo', 'bar', 'baz');
$prefix = uniqid();
$array = array_map(function ($elem) use ($prefix) {
return $prefix . $elem;
}, $array);
// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');
Answer from deceze on Stack Overflowuse is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the closure.
bar = function () {
// can't access $foo in here
echo $foo; // undefined variable
};
$baz = function () use ($foo) {
// $foo is made available in here by use()
echo $foo; // 42
}
For example:
$array = array('foo', 'bar', 'baz');
$prefix = uniqid();
$array = array_map(function ($elem) use ($prefix) {
return $prefix . $elem;
}, $array);
// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');
It is telling the anonymous function to make $connections (a parent variable) available in its scope.
Without it, $connections wouldn't be defined inside the function.
Documentation.
Videos
I work on a Symfony project which has/had a bunch of lines of code like this in them:
} catch (\Exception $e) {
I got into a habit of doing use Exception; at the top of the file as I felt the \ was a bit ugly, but i'm wondering if this is just personal preference or if there is a worthwhile reason to use the class/function explicitly rather than just using the backslash?
Is there anything in PSR that points to using one way or the other?
I'm using PHP 7.4.