Search code examples
phpcallbackscopearray-filter

Access a globally scoped variable inside of a callback function


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?


Solution

  • 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).