Modifying Variables in PHP Closures

Published 10th February 2017

This one caught me out yesterday. If you use a variable in a PHP closure and try and modify it inside the closure, you will find that the variable outside the closure is not modified. You must pass the variable by reference for it to work.

Turns out that when ‘importing’ variables to a closure’s scope they are actually being copied into the closure’s scope, rather than just being made available.

Note: This does not apply to objects because of the way object references work.