dou44481 2014-07-16 13:18
浏览 16
已采纳

PHP use()函数在这种情况下

I am trying to loop through a directory and only show files, no folders. I have come across this code from another person on SO, and while it works, I do not understand how.

function scandir_nofolders($d) {
    return array_filter(scandir($d), function ($f) use($d) {
       return ! is_dir($d . "/" . $f);
   });
}

So assume I have running this with the following code:

print_r(scandir_nofolders('/xampp');

Where I struggle is the inner most return value when the is_dir() function is determining whether the supplied parameter is a directory or not.

You'd think the code would translate to

return ! is_dir('/xampp'./.'/xampp');

Notice how in the above example $d and $f are the same. If you call an anonymous function and use the use function with in this case $d, wouldn't $d and $f be the exact same, because $f is essentially copying what $d is? Obviously I am not looking for /xampp//xampp (which is what I think the code would translate to), yet this works perfectly. Could someone explain what this code is actually doing? I imagine if anything, I have the true purpose of the use() function misunderstood.

  • 写回答

2条回答 默认 最新

  • dsolwotv00116 2014-07-16 13:26
    关注

    If you happen to know Javascript, the equivalent code there would be:

    function scandir_nofolders(d) {
        return scandir(d).filter(function (f) {
           return !is_dir(d + "/" + f);
       });
    }
    

    What's happening here? The innermost is_dir call uses a concatenation of d and f. d is the same d as was passed into the function, f is the value of one element in the array returned by scandir. In Javascript, variables of the parent scope of a function are available just like that inside a function.

    In PHP, that is not the case.

    $d = 'foo';
    function () {
        // no access to $d here
    }
    

    To make $d available inside the anonymous function, you need to "pass it through" using use. $d will be the parent directory and $f will be an entry within that directory.

    Also see Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件