我有以下代码但它们无效:
的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,我无法理解为什么我再次调用该函数...
有什么想法吗?
谢谢
答案 0 :(得分: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;
在任何地方使用适当的变量名称。