我编写了以下代码,以便找到在三个不同文件夹中添加的最新文件。我已将文件夹的目录存储在名为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
答案 0 :(得分: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();
答案 1 :(得分: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();