2016-07-20 145 views
0

在這裏發現了2個線程在Stackoverflow,這些是關於如何返回一個數組。我可以在函數內部生成一個數組,並且它具有正確的內容,但是當在函數外執行$ target_file的var_dumping時,它是NULL。否則,代碼正在做它應該做的事情。 它是一個範圍的東西?或者......我在這裏做了完全錯誤的事情嗎? 任何人都可以請幫助我訪問函數外的返回數組?訪問數組外部函數

function copy_files3($requested, $src_path, $send_path){ 
//function copy_files renames and copies pdf-files to a specific folder. 
//ARRAY $requested (keys INT), (names STR) holds the names of the selected files 
//STR $src_path is the full path to the requested files 
//STR $send_path is the full path to the re-named files 
//ARRAY $target_file holds the names of the renamed files 
    $i=0; 
    $target_file = array(); 
    $src_filename = array(); 
    $b=array(); 
    foreach($requested as $value) { 
     //$value holds the names of the selected files. 
     //1 Expand to get the full path to the source file 
     //2 Generate a 10 char + .pdf (aka 14 char) long new file name for the file. 
     //3 Generate full path to the new file. 
     $src_filename[$i] = $src_path.$value; 
     $rnam[$i] = randomstring(); //function randomstring returns a 10 char long random string 
     $target_file[$i] = $send_path.$rnam[$i].'.pdf'; 
     echo 'target_file['.$i.'] = '.$target_file[$i].'<br>'; 
     copy($src_filename[$i],$target_file[$i]); 
     $i++; 
    } 
    return($target_file); 
} 

我有文件重命名並放在我的服務器上正確的文件夾,唯一的問題是訪問此功能後的$ target_file數組。

+0

請出示你哪裏調用函數的代碼,並嘗試使用返回值 – Steve

回答

5

$target_file只存在於函數內。是的,這是一個範圍的事情。

您正在返回該變量的值,但變量本身。

您只需在調用函數時將返回的值賦給某個​​變量。現在

$returnedValue = copy_files3($requested, $src_path, $send_path); 

$returnedValue具有作爲$target_file有內部功能相同的值。

+0

中超,當然 - 總是很高興有別人看你的愚蠢的錯誤。謝謝。 – oldtimer

0
<?php 

function copy_files3($requested, $src_path, $send_path){ 
//function copy_files renames and copies pdf-files to a specific folder. 
//ARRAY $requested (keys INT), (names STR) holds the names of the selected files 
//STR $src_path is the full path to the requested files 
//STR $send_path is the full path to the re-named files 
//ARRAY $target_file holds the names of the renamed files 
    $i=0; 
    $target_file = array(); 
    $src_filename = array(); 
    $b=array(); 
    foreach($requested as $value) { 
     //$value holds the names of the selected files. 
     //1 Expand to get the full path to the source file 
     //2 Generate a 10 char + .pdf (aka 14 char) long new file name for the file. 
     //3 Generate full path to the new file. 
     $src_filename[$i] = $src_path.$value; 
     $rnam[$i] = randomstring(); //function randomstring returns a 10 char long random string 
     $target_file[$i] = $send_path.$rnam[$i].'.pdf'; 
     echo 'target_file['.$i.'] = '.$target_file[$i].'<br>'; 
     copy($src_filename[$i],$target_file[$i]); 
     $i++; 
    } 
    return($target_file); 
} 

$returnedValue = copy_files3($requested, $src_path, $send_path); 
?>