Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 943
Shoaib Nawaz Avatar asked Aug 31 '25 18:08

Shoaib Nawaz


1 Answers

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

use (&$total_strength)
   //^ See here
like image 125
Rizier123 Avatar answered Sep 02 '25 06:09

Rizier123