0

以下代码给了我以下错误,即使变量“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 使“主”范围内的变量也可用于函数。我想,我错了。谢谢您的帮助。

我已经使用“全局”语句修复了它。

4

2 回答 2

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
{
}
?>
于 2013-09-10T17:17:25.543 回答
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;
}
于 2013-09-10T17:22:18.217 回答