2014-07-07 83 views
-1

我有以下的代碼和他們沒有工作:PHP遞歸函數工作不正常:(

的index.php:

include("loadData.php"); 
    $my_var = loadData("myTxt.txt"); 
    var_dump($my_var); 

loadData.php:

function loadData($my_file){ 
     if(file_exists($my_file)){ 
      $file_contents = file_get_contents($my_file); 
      $file_contents = json_decode($file_contents); 
     }else{ 
      // If file doesn't exist, creates the file and runs the function again 
      $data_to_insert_into_file = simplexml_load_file("http://site_with_content.com"); 
      $fp = fopen($my_file, "w"); 
      fwrite($fp, json_encode($data_to_insert_into_file)); 
      fclose($fp); 
      // Since the file is created I will call the function again 
      loadData($my_file); 
      return; 
     } 

     // Do things with the decoded file contents (this is suposed to run after the file is loaded) 
     $result = array(); 
     $result = $file_contents['something']; 
     return $result; 
    } 

這第二次(在創建文件後)按預期工作,我可以在index.php上顯示信息,但是在第一次運行時(在創建文件之前)它始終顯示$ result爲NULL,我不能明白爲什麼我打電話給th e功能再次...

任何想法?

謝謝

+0

修復你的返回語句返回正確的值... – Phantom

+0

謝謝你的幫助:) – user2894688

回答

2

當你做你取你不返回任何東西:

if (...) { 
    $file_contents = file_get_contents(...); 
    // no return call here 
} else { 
    ... 
    return; // return nothing, e.g. null 
} 
return $result; // $result is NEVER set in your code 

你應該有return $file_contents。或更好:

if (...) { 
    $result = get cached data 
} else { 
    $result = fetch/get new data 
} 
return $result; 

通過使用適當的變量名到處。

+0

我已經編輯了這個函數,我忘記寫了返回$ result之前的最後兩行! – user2894688

+0

你仍然不會從你的fetch/fwrite部分返回任何東西,你只需'return;',這意味着調用上下文得到一個空值。 –

+0

但是當我再次調用函數時,我不會退出「當前」函數嗎? (停止當前操作) – user2894688