Modifying Variables in PHP Closures

Gilbert Pellegrom
Gilbert Pellegrom’s Blog
1 min readFeb 10, 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.

--

--

Gilbert Pellegrom
Gilbert Pellegrom’s Blog

Software Engineer from Scotland. Founder of @Dev7studioshq. Web Developer at @dliciousbrains.