0

我编写了以下代码以查找添加到三个不同文件夹中的最新文件。我已将文件夹的目录存储在一个名为 path 的数组中。我还将最新文件的名称存储在另一个数组中。

$path[0] = "/Applications/MAMP/htdocs/php_test/check";
$path[1] = "/Applications/MAMP/htdocs/php_test/check2";
$path[2] = "/Applications/MAMP/htdocs/php_test/check3";

for ($i=0; $i<=2; $i++){

$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';    

 $d = dir($path_last);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path_last}/{$entry}";
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
   }
  }

一切正常,但现在我尝试将相同的代码放在一个函数中并在我的主脚本中调用它。我使用此代码来调用它:

   include 'last_file.php'; // Include the function last_file
   $last_file = last_file();  // assign to the function a variable and call the function     

我不确定这是否正确。我想要做的是在我的主脚本中返回数组。我希望这里清楚我要解释的内容。感谢:D。

这是 last_file 函数:

    function last_file(){

        for ($i=0; $i<=2; $i++){

     $path_last = $path[$i]; // set the path
      $latest_ctime = 0;
       $latest_filename = '';    

      $d = dir($path_last);
     while (false !== ($entry = $d->read())) {
      $filepath = "{$path_last}/{$entry}";
      // could do also other checks than just checking whether the entry is a file
       if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
        $latest_ctime = filectime($filepath);
        $latest_filename = $entry;
     $array[$i] = $latest_filename ; // assign the names of the latest files in an   array.
        }
      }

    return $array;

      }//end loop
      }//end function
4

2 回答 2

2

您将函数文件混淆了。您的代码放在文件中。在这些文件中,您可以定义函数

<?php
// This is inside last_file.php

function someFunction {
    // Do stuff.
}

someFunction()在另一个文件中使用,您首先包含last_file.php然后调用someFunction()

<?php
// This is inside some other file.

include 'last_file.php';

someFunction();
于 2012-11-10T20:05:52.610 回答
1

如果你把它放在一个函数中,你需要像这样返回它。

function func_name()
{
$path[0] = "/Applications/MAMP/htdocs/php_test/check";
$path[1] = "/Applications/MAMP/htdocs/php_test/check2";
$path[2] = "/Applications/MAMP/htdocs/php_test/check3";

for ($i=0; $i<=2; $i++){

$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';    

 $d = dir($path_last);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path_last}/{$entry}";
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
return $array;
}

然后,当您调用该函数并将其分配给变量时,您将获得 $array 的内容

$contentsFromFunction = func_name();
于 2012-11-10T20:04:53.880 回答