Aristona
Aristona

Reputation: 9351

Is there any difference between function($var) and function() use ($var)?

Is there any differences between those?

$something = function($var) { 

});

$something = function() use ($var) {

});

Upvotes: 0

Views: 546

Answers (2)

mjk
mjk

Reputation: 2453

The former is a function with a single parameter named $var. If there's another $var defined elsewhere in the script, it doesn't matter; the function won't contain a reference to it inside its scope (within its definition).

For example.

$bar = 3;
function foo($bar) {
   if (isset($bar)) {
      echo "bar: $bar";
   } else {
      echo "no bar";
   } 
}
foo(10); // prints "bar: 10", because the function is called with the argument "10"
foo(); // prints "no bar" -- $bar is not defined inside the function scope

In the case of the latter, the use $var closure means that a definition of $var in the containing scope will be accessible, like a global variable, inside the function.

For example,

$bar = 3;
function foo($blee) use $bar {
   if (isset($bar)) {
      echo "bar: $bar";
   } else {
      echo "no bar";
   }
   if (isset($input)) {
      echo "input: $input";
   } else {
      echo "no input";
   }
}
foo(1); // prints "bar: 3, input: 1"
foo(); // prints "bar: 3, no input"

Upvotes: 2

knittl
knittl

Reputation: 265546

The first one is a function taking a single parameter, the other one is a function taking no parameters and closing over the value of the variable $var from the parent scope.

Upvotes: 1

Related Questions