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.

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

报告相同问题?

悬赏问题

  • ¥15 Android STD快速启动
  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动