【问题标题】:The property assigned to the stdClass() becomes empty after the function ends (global)函数结束后分配给 stdClass() 的属性变为空(全局)
【发布时间】:2019-09-24 16:01:58
【问题描述】:

我正在尝试从文件夹内的文件夹中获取文件名(../merchant_assets/ 文件夹内有一个名为 1 的文件夹,我正在尝试获取该文件夹内的所有名称文件)

下面的代码工作正常,但是当我将包含结果$temp 的数组分配给stdClass() 变量$container 时,当我尝试在函数print_r($container->screenshots) 之外打印出数组时,它变为空但是如果我在函数内部打印出来它就可以了

<?php 
include 'config.php';

$url = "http://" . $_SERVER['HTTP_HOST'] . '/merchant_assets/';
$target = '../merchant_assets';

$merchant_id = 1;

$container = new stdClass();

$folder = '';

// Call the function
dir_contents_recursive($target);

// Get all screenshots images from merchant_assets folder based on merchant_id
function dir_contents_recursive($dir) {

    // open handler for the directory
    global $container;
    $iter = new DirectoryIterator($dir);
    $temp = Array();
    foreach( $iter as $item ) {

        // make sure you don't try to access the current dir or the parent
        if ($item != '.' && $item != '..') {

            if( $item->isDir() ) {

                // call the function on the folder
                global $merchant_id, $folder;

                if($merchant_id == $item->getFilename()) {

                    $folder =  $item->getFilename();
                    dir_contents_recursive("$dir/$item");
                }else 
                    continue;
            } else {

                // print files
                global $url, $folder;
                $current_index = count($temp);
                $temp[$current_index] = $url . $folder . '/' . $item->getFilename();
            }
        }
    }
    $container->screenshots = $temp;

    print_r($container->screenshots); // It shows the results
}

// Handle response
$response = $container;

print_r($container->screenshots); // No results???

$response_json = json_encode($response);
echo $response_json;
?>

我希望输出是 [我故意将每个索引的值改为item]

Array ( 
[0] => item 
[1] => item 
[2] => item 
[3] => item 

【问题讨论】:

  • 不能在函数外调用$container
  • @fmsthird 实际上他可以作为 $container 的原始定义在函数之外。但我不建议使用全局变量。为什么不从函数中返回对象?

标签: php arrays class object


【解决方案1】:

问题是您的递归调用没有将数据分配给$temp

在你的函数开始时你取消$temp = Array(); - 但你永远不会对他使用全局。

所以第一次调用函数时,$temp 是空数组,if( $item-&gt;isDir() ) 是 TRUE,所以它进入 递归。在那里,您确实将元素添加到 $temp 并分配 $container-&gt;screenshots(这样打印效果很好)。

但是,退出递归调用后,您再次将 $temp 分配给 $container-&gt;screenshots,但在此范围内 $temp 数组! (没有结果)。

我强烈建议不要在这里使用全局,而是返回文件数组作为递归函数返回参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-06
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多