duanseci1039 2019-02-04 15:53
浏览 61
已采纳

从PHP函数中传递变量[重复]

I'd like to report how many files get deleted from a function that I'm running within php via a cron task.

Current codes is as follows:-

<?php

function deleteAll($dir) {
    $counter = 0;
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file)) {
            deleteAll($file); }
        else {
            if(is_file($file)){
// check if file older than 14 days
                if((time() - filemtime($file)) > (60 * 60 * 24 * 14)) {
                    $counter = $counter + 1;
                    unlink($file);
                } 
            }
        }
    }
}   

deleteAll("directory_name");

// Write to log file to confirm completed
$fp = fopen("logthis.txt", "a");
fwrite($fp, $counter." files deleted."."
");
fclose($fp);

?>

That makes sense to me with a VBA background, but the counter returns null I think when written to my custom log file at the end. I presume there is some restriction on a shared hosting site of being able to declare the variable globally or similar?

Appreciate any help! It's not the end of world if I can't count the deleted files, but it would be nice to log the output in the format I've chosen.

</div>
  • 写回答

1条回答 默认 最新

  • ds20021205 2019-02-04 15:55
    关注

    This doesnt work due to scopes. In your example $counter only exists inside your function.

    function deleteAll($dir):int {
        $counter = 0; // start with zero
        /* Some code here */
        if(is_dir($file)) {
            $counter += deleteAll($file); // also increase with the recursive amount
        }
        /* Some more code here */
        return $counter; // return the counter (at the end of the function
    }
    
    $filesRemoved = deleteAll("directory_name");
    

    Alternatively, if you want to send back more info, eg 'totalCheck' etc, you can send back an array of info:

    function deleteAll($dir):array {
        // All code here
        return [
            'counter' => $counter,
            'totalFiles' => $allFilesCount
        ];
    }
    $removalStats = deleteAll("directory_name");
    echo $removalStats['counter'].'files removed, total: '.$removalStats['totalFiles'];
    

    There are other solutions like 'pass-by-reference', but you dont want those.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?