1

One way to bring an outside variable inside a scope is by using the use keyword in PHP.

My question is, why can we only do it on a closure/anonymous function and not on a regular function:

$func = function() use ($globalVar) {}; // this works

function func() use ($globalVar) {} // this  won't work. Why?
Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
  • https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier – waterloomatt Nov 18 '19 at 18:19
  • Because you can use `global $globalVar` or `$GLOBALS['globalVar']` – AbraCadaver Nov 18 '19 at 19:05
  • it works see this example `` displays `HelloWorld` and the function has an access to `$add`. The second function in your example isn't a regular function but also an anonymous function that uses closure. In the second example you simply don't use the function. Hence the lack of any effect. – Jimmix Nov 18 '19 at 19:31

0 Answers0