扫描目录下的文件请看下面的函数(摘自here)
function scandir_only_files($dir) {
return array_filter(scandir($dir), function ($item) {
return is_file($dir.DIRECTORY_SEPARATOR.$item);
});
}
这不起作用,因为 $dir 不在匿名函数的范围内,并且显示为空,导致过滤器每次都返回 FALSE。我将如何重写它?
最佳答案
您必须使用 use
关键字显式声明从父作用域继承的变量:
// 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);
});
}
参见 this example来自匿名函数页面。
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).
关于php - 帮助 PHP array_filter 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380590/