[英]How to return an array from a function to the main script
我編寫了以下代碼,以查找添加到三個不同文件夾中的最新文件。 我已經將文件夾的目錄存儲在名為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
您正在將函數與文件混淆。 您的代碼放在文件中 。 在這些文件中,您可以定義函數 :
<?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();
如果將其放在函數中,則需要像這樣返回它。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.