Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

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

share|improve this answer
 
+1 for Use use –  tttony Sep 11 '11 at 19:20
 
@arnaud- awesome- just learned something new! –  Yarin Sep 11 '11 at 19:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.