PHP, Closures, use & references
I want to talk about one feature of using closures in PHP-5.3. I think for many it will seem obvious, but nonetheless. It turns out using use ($ var1, ..) - we can pass variables by reference: use (& $ var1, ..).
An example illustrating possible use cases (and please do not poke your nose into array_sum () ;)):
At the output we get:
Enjoy!
An example illustrating possible use cases (and please do not poke your nose into array_sum () ;)):
$ rows = array (1, 2, 3);
$ total = 0;
// Case of times - use ($ total) without reference
array_walk ($ rows, function ($ row) use ($ total) {
$ total + = $ row;
});
echo "Total is $ total \ n";
// Case two - use (& $ total) by reference
array_walk ($ rows, function ($ row) use (& $ total) {
$ total + = $ row;
});
echo "Total is $ total \ n";
At the output we get:
Total is 0 Total is 6
Enjoy!