首页 > 解决方案 > 从 PHP 函数中传递变量

问题描述

我想报告通过 cron 任务从我在 php 中运行的函数中删除了多少文件。

当前代码如下:-

<?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."."\n");
fclose($fp);

?>

这对具有 VBA 背景的我来说很有意义,但是我认为当最后写入我的自定义日志文件时,计数器返回 null。我认为共享托管站点对能够全局声明变量或类似的变量有一些限制?

感谢任何帮助!如果我不能计算已删除的文件,这不是世界末日,但是以我选择的格式记录输出会很好。

标签: phpfunctionvariablesreturnunlink

解决方案


由于范围,这不起作用。在您的示例$counter中,仅存在于您的函数内部。

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");

或者,如果您想发回更多信息,例如“totalCheck”等,您可以发回一组信息:

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

还有其他解决方案,例如“通过引用”,但您不想要那些.


推荐阅读