Search code examples
phpphp-5.6php-closures

Is there a way to update caller scope variables from php closure


use keyword with php closure is a pretty clear way to extend the scope of handpicked variable to closure.

Is there any way if we need to update the value of some variable in caller function scope from closure?

$total_strength = 0;
$all_cores->each(function($core) use ($total_strength) {
    $total_strength += $code->strength;
});

print('Cumulative cores' strength is: ' . $total_strength);

Here I always get 0. How to fix that?


Solution

  • You can simply pass the argument by reference, Like this:

    use (&$total_strength)
       //^ See here