PHP use () function for scope?

I saw a code like this:

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

but php.net does not seem to mention this feature. I guess this is related to scope, but how?

+6
source share
2 answers

use not a function; it is 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 instance:

 $array = array('foo', 'bar', 'baz'); $prefix = uniqid(); $array = array_map(function ($elem) use ($prefix) { return $prefix . $elem; }, $array); // $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz'); 
+8
source

Tells an anonymous function to make $connections (the parent variable) available in its scope.

Without it, $connections will not be defined inside the function.

Documentation

+3
source

Source: https://habr.com/ru/post/900011/


All Articles