以下代码给出了以下错误,甚至认为变量'cache_path'已在顶部定义。
<b>Notice</b>: Undefined variable: cache_path in <b>C:\Users\Jan Gieseler\Desktop\janBSite\Scripts\Index.php</b> on line <b>20</b><br />
这是代码;
header('Content-type: application/x-javascript');
$cache_path = 'cache.txt';
function getScriptsInDirectory(){
$array = Array();
$scripts_in_directory = scandir('.');
foreach ($scripts_in_directory as $script_name) {
if (preg_match('/(.+)\.js/', $script_name))
{
array_push($array, $script_name);
}
}
return $array;
}
function compilingRequired(){
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}
if (compilingRequired())
{
}
else
{
}
?>
我该怎么做才能解决这个问题?
编辑:我认为PHP也会使“主要”范围内的变量可用于函数。我想,我错了。谢谢你的帮助。
我已经使用'global'语句修复了它。
答案 0 :(得分:2)
为了完全理解这一点,你必须阅读可变范围,祝你好运!
header('Content-type: application/x-javascript');
$cache_path = 'cache.txt';
function getScriptsInDirectory(){
$array = Array();
$scripts_in_directory = scandir('.');
foreach ($scripts_in_directory as $script_name) {
if (preg_match('/(.+)\.js/', $script_name))
{
array_push($array, $script_name);
}
}
return $array;
}
function compilingRequired($cache_path){ //<-- secret sauce
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}
if (compilingRequired($cache_path)) //<-- additional secret sauce
{
}
else
{
}
?>
答案 1 :(得分:1)
你的$ cache_path在函数内部是未知的。要么将它作为像MonkeyZeus建议的参数给出,要么在函数内使用global $cache_path
。
function compilingRequired(){
global $cache_path; // <------- like this
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}