7

Please see the following function to scan the files in a directory (Taken from here)

function scandir_only_files($dir) {
   return array_filter(scandir($dir), function ($item) {
       return is_file($dir.DIRECTORY_SEPARATOR.$item);
   });
}

This does not work because the $dir is not in scope in the anonymous function, and shows up empty, causing the filter to return FALSE every time. How would I rewrite this?

Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512

1 Answers1

16

You have to explicitly declare variables inherited from the parent scope, with the use keyword:

// use the `$dir` variable from the parent scope
function ($item) use ($dir) {

function scandir_only_files($dir) {
   return array_filter(scandir($dir), function ($item) use ($dir) {
       return is_file($dir.DIRECTORY_SEPARATOR.$item);
   });
}

See this example from the anonymous functions page.

Closures may inherit variables from the parent scope. Any such variables must be declared in the function header. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194