39

I have seen code like this:

function($cfg) use ($connections) {}

but php.net doesn't seem to mention that function. I'm guessing it's related to scope, but how?

3 Answers 3

65

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.

$foo = 42;

$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');
Sign up to request clarification or add additional context in comments.

Comments

6

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.

1 Comment

It should be noted that $connections would not be null; it would be an undefined variable if it wasn't explicitly imported into the anonymous function's scope with use ($connections).
2

Just an addition to the answer

$bok = fn() => "don't need to use $foo";

echo $bok(); // don't need to use 42

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.