【问题标题】:Why don't i have scope to access values in a recursiveDirectoryItorator?为什么我没有范围访问 recursiveDirectoryItorator 中的值?
【发布时间】:2013-04-01 06:48:38
【问题描述】:

我正在使用 PHP RecursiveDirectoryItorator,但我发现由于某种原因,我的一些变量应该在范围内时超出了范围......除非我真的错过了一些东西。我试图访问的两个变量是 $master_array 和 $current,如果我在 else 语句中 echo 或 print_r 它们都没有任何值。这是我的代码:

$master_array = array(); 

$startpath = "some file path"; // i'm using a real file path in my code. 
$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($startpath), RecursiveIteratorIterator::CHILD_FIRST); 

foreach($ritit as $fileinfo) {
    echo "<pre>"; 
    $current = ''; 
    if(!$fileinfo->isFile()) {

        if(strip_replace($fileinfo->getFilename()) == strip_replace('some  - title')) {
            $master_array[$fileinfo->getFilename()]  = $fileinfo->getPathname(); 
            $current = $fileinfo->getFilename(); 
        } 

    } else {

        if(!empty($current) && in_array($current, split_file_path_into_array($fileinfo->getPathname()))) {
            echo $fileinfo->getFilename()."\n"; 
            echo $fileinfo->getPathname()."\n"; 
        } 
        echo $current; // i don't have access to this
        print_r($master_array); // and i don't have access to this.  

        }
    }   

对此的任何帮助将不胜感激。我希望我只是忽略了一些简单的事情,但是我一直在查看这段代码,并且把它弄乱了很长一段时间,似乎无法让它工作。

【问题讨论】:

    标签: php iterator scope


    【解决方案1】:

    $current 应该是数组而不是字符串

    $current = array();
    

    $current 将始终为空,因为您在 else 中调用它并在 if's if 中赋值。

    【讨论】:

    • 我试过了......它什么也没做。它不起作用的一个例子是我什至试图打印出 $master_array... 如果我在 if 语句或 else 语句之外调用它,它会打印出一个值。所以我真的很困惑。不过,我感谢您的快速回复。
    • @AlexW.H.B.可能是您的条件从未满足,结果只是其他部分。尝试适当的调试。
    • 我同意您的说法“$current 将始终为空,因为您在 else 中调用它并在 if 的 if 中赋值。”这是有道理的......但我现在不明白的是,为什么 $master_array 没有价值,当它具有比 foreach 循环更高的范围时。我会尝试调试它...好建议。
    • @AlexW.H.B.可能是您的条件从未满足,结果只是其他部分,它永远不会将值分配给$master_array
    猜你喜欢
    • 2014-01-27
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多