7

I know what the use operator is doing in something like function($x,$y) use ($z) { ...

What I don't understand is why PHP uses this construction when other languages don't?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Cameron Ball
  • 4,048
  • 6
  • 25
  • 34
  • 1
    possible duplicate of [Why PHP variables start with a $ sign symbol?](http://stackoverflow.com/questions/3073812/why-php-variables-start-with-a-sign-symbol) – Meenesh Jain Aug 17 '15 at 06:55
  • 4
    My spontaneous tip would be that PHP's scope engine cannot efficiently deal with the problem otherwise and explicitly extending the scope of variables was simpler to implement. Again, just a guess though. – deceze Aug 17 '15 at 07:24
  • The [RFC for closures and lambdas](https://wiki.php.net/rfc/closures) seems to get close to an answer, but appears to cover more of the _what_ than the _why_. – HPierce Aug 17 '15 at 12:57
  • Because PHP is not "other languages"?! – axiac Sep 03 '15 at 20:19

1 Answers1

0

Javascript has rather loose variable scoping (you don't need to declare variables as global). PHP has tighter variable scoping (if a variable isn't defined within the scope that it's used, and isn't brought in with global, then it doesn't exist).

The use declaration tells PHP to make those variables available within the closure (and likely also tells the garbage collector not to clean them up until after the closure gets cleaned up).

samlev
  • 5,852
  • 1
  • 26
  • 38