PHP全局计数不会重置


PHP global count does not reset

我正试图编写一个函数,在一种情况下(在许多情况下)循环遍历文件时对图像进行计数,我在函数copyInsertImage中声明了变量$imageCount全局,以便在图像成功插入数据库后,我执行$imageCount++

在处理完案例的所有图像后,代码退出循环,函数processImages将再次调用。然而,我做了一个var_dump($imageCount),每次图像计数增加1时都会打印出来,并发现在为新情况运行循环时,$imageCount = 0从未将其重置回0。

我想知道声明global $imageCount是否与此有关,因为在将同一脚本分组为函数之前,代码以前工作得很好。如果是,解决方案是什么?

谢谢!

function processImages($path,$patientID,$caseID)
{
    // $path = rootDirectory/patientID
    global $targetDirectory;
    $targetPath = $targetDirectory.$patientID;

    $caseSummaryFolder = $path."/".$caseID."/Summary";
    $srcDirPath=$path."/".$caseID."/Summary/slicesdir"; //AKA src
    $dstDirPath = $targetPath."/".$caseID;
    //copyCaseImages($caseSummaryFolder,$targetCasePath,$patientID,$caseID);
    global $status;
    // print("processImages case path:".$casePath."</br>");
    $files = glob($srcDirPath."/*.png");
    echo "'n------------NEW CASE------------'n"
    echo "PATIENT: $patientID 'n";
    echo "CASE: $caseID 'n";
    echo "--------------------------------'n"
    $imageCount = 0;
    for($i = 0; $i < count($files); $i++) {
        $file = $files[$i];
        $fileName = str_ireplace($srcDirPath."/", "", $file);
        // if image name doesn't not contain string 'GROT'
        if(strripos($fileName, "grot") === false)
        {
            if(doesImgExist($fileName)!==NULL) {
                if (compareFileMTime($srcDirPath,$fileName,doesImgExist($fileName))) {
                    echo "There's a newer version of $fileName 'n";
                    copyInsertImage($srcDirPath,$dstDirPath,$fileName,$patientID,$caseID);
                }
                else {
                    $imageCount++;
                }
            }
            // copy image to analyzedCp and insert new image into DB
            else {
                copyInsertImage($srcDirPath,$dstDirPath,$fileName,$patientID,$caseID);
            }
        }   
        else {
            echo "grot*.png files are not included 'n";
        }
    }

如果我正确理解了你的问题,那么你似乎在"copyInsertImage"函数中重新定义了"global$imageCount",而这个函数是for循环的一部分。如果这确实是你遇到的问题,那么问题是,每当你的for循环命中"copyInsertImage"函数时,它都会重新声明$imageCount,这个重新声明会使imageCount成为一个新变量,并清除你存储在其中的任何内容。这可能是你看到$imageCount=0的原因。

@andrewsi回答了我的问题。

通过将最初的$imageCount声明为global,我的问题也得到了解决。

"如果你使用全局变量,你需要在每个使用它们的函数中将它们声明为全局变量。否则,你最终会使用一个同名的局部变量。这也是尽可能避免使用它们的原因之一——当你需要变量时,更容易将变量传递到函数中。"

谢谢!