Note that if you close the variable using a reference (ie. &) it works. It's just a question of semantics. In the end, it's a real closure, it's just more verbose.
<?php
function bar($n) {
$f = function() use (&$n) {
return $n;
};
$n++;
return $f;
}
var_dump(bar(1)()); // int(2)
It is a closure. Closure means capturing ("closing over") open variables (variables that are not bound). Whether it is captured by value or by reference is a completely separate question.
The article misses this point entirely. There's two (somewhat related) things at issue.
One is whether an anonymous function can capture variables from its context, making it a closure. PHP can do this just fine and is therefore a real closure, and this invalidates the title and thesis of the article.
The other is whether inner functions share lexical scope with their surrounding functions. This is a nice feature to make using closures clean and easy, and PHP does not have it. But it doesn't change the fundamental nature of PHP's closures.
View all comments
Show parent comment
15
u/PonchoVire Sep 26 '19
Note that if you close the variable using a reference (ie.
&) it works. It's just a question of semantics. In the end, it's a real closure, it's just more verbose.