Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use() function for scope?

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?

like image 1000
kristian nissen Avatar asked Oct 25 '11 06:10

kristian nissen


People also ask

What is scope of function in PHP?

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used.

What is the use of use function in PHP?

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. Show activity on this post. It is telling the anonymous function to make $connections (a parent variable) available in its scope.

What is use of isset () function?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

How can I access one function variable from another function in PHP?

php Class First { private $a; public $b; public function create(){ $this->a=1; //no problem $thia->b=2; //no problem } public function geta(){ return $this->a; } private function getb(){ return $this->b; } } Class Second{ function test(){ $a=new First; //create object $a that is a First Class.


2 Answers

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'); 
like image 142
deceze Avatar answered Sep 25 '22 02:09

deceze


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.

like image 37
alex Avatar answered Sep 23 '22 02:09

alex