【问题标题】:Pass variable from within PHP function [duplicate]从PHP函数中传递变量[重复]
【发布时间】:2019-06-28 09:45:12
【问题描述】:

我想通过 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。我认为共享托管站点在能够全局声明变量或类似变量方面存在一些限制?

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

【问题讨论】:

  • 有函数return $counter。现在,您正在处理一个范围问题,即在您的 fwrite() 调用中使用的 $counter 与您的函数内部不同。
  • 只是范围问题。详情请查看this questionthis question

标签: php function variables return unlink


【解决方案1】:

由于范围,这不起作用。在您的示例中,$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'];

还有其他的解决方案,比如'pass-by-reference',但是你dont want those

【讨论】:

  • 以下一些 PHP 函数的替代:function deleteAll($dir, &amp;$counter) 然后调用为 deleteAll("directory_name", $filesRemoved); 但我只会在函数需要返回其他内容时使用它。
  • 即使那样我也会改变函数,所以我不必参考。 IMO 这是一种代码味道。
  • 谢谢大家 - 快速响应!我想我已经明白了,这只是一个与 VBA 不同的概念,基于我认为你不能声明变量的范围。
  • 嗯。仍然有这个问题。在我的代码中,我修改为使用 "$filesRemoved = deleteAll("dir_name"); 调用函数并添加了 "return $counter;在测试文件年龄的“if”末尾。但这对我有帮助。如果我在 if 语句的最后一个子子句中添加“return $counter”,则不会引发错误,但它只会返回“0”。
  • @Martijn 所以我已经修改了我的代码以根据你的第一个建议添加'return $counter',但我得到的只是我将'$counter'设置为的默认值开始。我可以在 if 语句中输出增量计数,但最后没有发送。我显然在做一些愚蠢的事情,但看不到它!
猜你喜欢
  • 2012-08-20
  • 2011-03-13
  • 2023-01-11
  • 2014-05-14
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
相关资源
最近更新 更多