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

1.5k Views Asked by At

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?

1

There are 1 best solutions below

0
Rizier123 On BEST ANSWER

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

use (&$total_strength)
   //^ See here