add(function($req, $res, $next) { # closure A $res->on...">

PHP closure in another closure: "use" scope

I have a code that looks like this:

$app->add(function($req, $res, $next) {
    # closure A
    $res->on('end', function($res) use ($req) {
        # closure B
    });
    $next();
});

As you can see, I have closure in closure. Closing B receives a $resresponse from the event, so there is no problem with it. But out of circuit And also useing $req. Here I have doubts about the scope of the variable use'd, I see two possibilities:

  • Any response will have its own request object, because closure B is recreated for each new listener passed in $res->on. Thus, there are many closures B with its domain inherited once from the closure variable A.
  • Or any new request to replace $req, and $resthe closing of A (normal behavior ...), but also replace the $reqused pre-made circuits B. And it would be problematic if the request # 1 does not respond to the query will go β„–2 (this is an asynchronous event loop code).

I hope I'm clear enough. I ask this because, for example, in JavaScript, we sometimes have to use callback generators to ensure that the subtitle area is not replaced.


Edit: I tried with code that theoretically does the same thing, but which is easier to verify:

$a = function($var) {
    return function() use ($var) {
        var_dump($var);
    };
};

$fn1 = $a((object) ['val' => 1]);
$fn2 = $a((object) ['val' => 2]);
$fn2();
$fn1();

(2, 1) , $fn1 . , , var_dump Closure , :

object(Closure)#3 (1) {
  ["static"]=>
  array(1) {
    ["res"]=>
    object(stdClass)#2 (1) {
      ["val"]=>
      int(1)
    }
  }
}

? , PHP PHP, use .

? PHP?

+4
1

Closure PHP -. , use. PHP -.

use , , . "" , . , , .

$var1 = 1;
$var2 = 2;

$closure = function () use ($var1, $var2) {
    return $var1 . ", " . $var2 . "\n";
};

$array = [$var1, $var2];

$var1 = 3;
$var2 = 4;

echo $closure(); // echoes 1, 2
echo $array[0] . ", " . $array[1] . "\n"; // echoes 1, 2

$var1 $array[0], $var1 $closure.

, , . . , , .

. , .

$var1 = 1;
$var2 = 2;

$closure = function () use (&$var1, $var2) {
    return $var1 . ", " . $var2 . "\n";
};

$array = [&$var1, $var2];

$var1 = 3;
$var2 = 4;

echo $closure(); // echoes 3, 2
echo $array[0] . ", " . $array[1] . "\n"; // echoes 3, 2

, $var1, $var2 . $var1 $var2 , $var1 , . - , $var1 , $var2 .

, . , .

$value = 1;

$closure = function ($arg) use ($value) {
    return function () use ($arg, $value) {
        return $value + $arg;
    };
};

$value = 10;

$callback1 = $closure(1);
$callback2 = $closure(2);

echo $callback1() . "\n"; // Echoes 2
echo $callback2() . "\n"; // Echoes 3

TL; DR: . , (, function () use (&$value) { ... }).

+3

All Articles