📜 ⬆️ ⬇️

PHP, Closures, use & references

I want to talk about one particular use of closures in PHP-5.3. I think for many it will seem obvious, but nonetheless. It turns out that using use ($ var1, ..) - we can pass variables by reference: use (& $ var1, ..).

An example illustrating possible uses (and please do not stick your nose at 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!

')

Source: https://habr.com/ru/post/69003/


All Articles