February 10, 2017

Modifying Variables in PHP Closures

<iframe width="560" height="315" src="https://www.youtube.com/embed/nWIP74H2Vl4?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> <p>This one caught me out yesterday. If you <code>use</code> a variable in a <a href="http://php.net/manual/en/functions.anonymous.php">PHP closure</a> 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.</p> <script src="https://gist.github.com/gilbitron/5020cb89a85f66075d2a4e0128d14631.js"></script> <p>Turns out that when ‘importing’ variables to a closure’s scope they are actually being <strong>copied</strong> into the closure’s scope, rather than just being made available.</p> <p><strong>Note</strong>: This does not apply to objects because of the way <a href="http://php.net/manual/en/language.oop5.references.php">object references work</a>.</p>