【问题标题】:PHP says variable doesn't exist - even though it doesPHP说变量不存在 - 即使它存在
【发布时间】:2013-09-10 17:16:05
【问题描述】:

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

我已通过使用“全局”语句修复它。

【问题讨论】:

标签: php variables scope


【解决方案1】:

为了完全理解这一点,您必须阅读变量作用域,祝您好运!

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
{
}
?>

【讨论】:

  • 你是不是忘记把compilingRequired()里面的参数传进去了?
【解决方案2】:

您的 $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;
}

【讨论】:

    猜你喜欢
    • 2012-01-24
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多