0

In what situation is using the use keyword with a closure more beneficial then just passing along additional parameters to the closure?

Example #1:

$myClosure = function($var1, $var2) use ($var3){
//Some code
}

Example #2:

$myClosure = function($var1, $var2, $var3){
//Some code
}

Like all things it probably depends, but I don't see any functional difference between the two. Can anyone suggest a situation or example where one example would be preferred over the other?

d.lanza38
  • 2,525
  • 7
  • 30
  • 52

2 Answers2

1

I don't see any functional difference between the two.

The arguments are provided by the caller of the function. If you are the caller and can provide all the necessary arguments, then there is basically no difference*.

However, you might be passing the function somewhere else, so you are not caller and do not control which arguments are passed. This is the situation that closures solve: You can make values available without calling the function.

See also In PHP 5.3.0, what is the function "use" identifier? .


*: The variables that are bound through use are defined at definition time. So if the value of the variable changes, there will be a difference:

$a = 1;
$b = 2;
$c = 3;

$f1 = function($a, $b) use ($c) {
  echo $a, $b, $c;
};

$f2 = function($a, $b, $c) {
  echo $a, $b, $c;
};

$c = 42;

$f1($a, $b); // 1, 2, 3
$f2($a, $b, $c); // 1, 2, 42
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Okay, now I get the difference. I actually read through the link you provided before asking this question, but in the bit about scope I just interpreted that as the scope in the function is different than outside the function which I understand. I didn't realize the value passed in the `use` clause was passing the value of the variable at the time of declaration rather than at the time of calling. Reading the answer again, I guess that is what they meant by "early binding". Thank you for your answer, it makes more sense now. – d.lanza38 Oct 24 '16 at 15:46
0

Say you're using a closure with pre-defined parameters, like preg_replace_callback for example, and you want to use a variable from other places in your code, you'd use the use keyword

$myvar = "hello";
$text = "";
$text = preg_replace_callback('/regex/', function($matches) use ($myvar) {
  return $myvar . " " . $matches[1] . "!";
}, $text);

It's a great way to use a variable within a closure with pre-defined parameters, which do not have access to variables outside the closure

Pazuzu156
  • 679
  • 6
  • 13