2014-07-07 156 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