10 February 2017

Modifying Variables in PHP Closures

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.

Looking for more?

Subscribe to my newsletter to get infrequent updates in your inbox. Or follow me on Twitter.