Shoaib Nawaz
Shoaib Nawaz

Reputation: 2320

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?

Upvotes: 4

Views: 1753

Answers (1)

Rizier123
Rizier123

Reputation: 59681

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

use (&$total_strength)
   //^ See here

Upvotes: 13

Related Questions