php - 从 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。我认为共享托管站点对能够全局声明变量或类似的变量有一些限制?
感谢任何帮助!如果我不能计算已删除的文件,这不是世界末日,但是以我选择的格式记录输出会很好。
解决方案
由于范围,这不起作用。在您的示例$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'];
还有其他解决方案,例如“通过引用”,但您不想要那些.
推荐阅读
- c - 重新解释适当对齐的指向具有声明类型的对象的指针
- vue.js - 生产中 ie11 中的 vue-cli3 语法错误
- c# - 如何在 Windows UWP 应用程序中制作径向仪表
- logging - 使用 Full_Audit 监控 Samba 活动
- esp8266 - esp8266 客户端和服务器同时进行
- bash - 在 Azure 容器中持续运行 bash 脚本
- c++ - 以下哪些是有效的 C++ 变量名?
- python - 用于从列表中查找特定字符串的正则表达式格式
- python-3.x - python中的排列和randint有什么区别?
- python - 多数据序列的多元时间序列分析