PHP Gotcha! Closures don't automatically inherit scope

This caught a co-worker yesterday. He had written a block of code similar to this…


function foo ( $array, $param ) {
  array_walk( $array, function( &$value ) {
    $value .= ' '.$param;
  });
}

His expectation was that $param would be seen in the scope of the closure, just as it would be in Java Script. In PHP this isn’t the case, the use statement is required for this functionality.


function foo ( $array, $param ) {
  array_walk( $array, function( &$value ) use ( $param ) {
    $value .= ' '.$param;
  });
}

Something to keep in mind. Anyone else come across a Gotcha! of late?

Not that I know of :shifty:

But I’m willing to bet I got some old code that could use a tweak with this knowledge.

Because it hasn’t caused a problem for me I can hopefully avoid poring over massive amounts of code.

But from now on when my eyes see code I’ll remember this and if a problem does happen I’ll know this might be involved.

Thanks.

Since closures were introduced in PHP, I’ve always had to keep it in mind that in PHP they’re “special” in the sense that the variables have to explicitly imported (with “use”) into the closure. Do I still sometimes forget? Of course! When every other language that I regularly use (that has closures) doesn’t have this requirement, it’s easy to forget. (:


var_dump(in_array("foo", array(0)));

Guess what that evaluates to …
Indeed: true :shifty:

From: https://twitter.com/fabpot/status/460707769990266880

That is a really basic principle of closures in php… not really a gotcha if you take the time to read the docs :confused:

PHP ain’t JavScript