php全局变量dos';不能在包含的文件中工作


php global variable doesn't work inside included file

我已经找了一天的时间来找到解决方案,但还没有运气,我有一个名为:online()的函数,该函数位于名为client.php的文件中,该文件位于root/dir/includes/client.php中:

在client.php中:

// db connection
include "base.php";
// check if availabe
$available = "false";
$check = mysql_query("SELECT available FROM users ");
while ($row=mysql_fetch_array($check)) {
    if($row['available'] == "yes") {
        $available = "true";
    }
}
// get config
$fetch = mysql_query("SELECT * FROM config ");
$config = mysql_fetch_array($fetch);
// functions
function online() {
// globals
global $available,$config,$path;
// build box
    if($available == "true") {
        ?>
        <div id="online">
        <?
    } else {
            ?><div id="offline"> <?
        }
echo 'client.php is included';
}
}
?>

关于client.php:

它首先建立数据库连接,然后检查用户是否可用,如果可用:$available = "true";其他:$available = "false";

然后我将client.php包括在index.php中(位于根中),因此我有:

在index.php中:

$path = "dir/";
include $path . "includes/client.php";

到目前为止一切都很好

问题是

我也需要在子目录中的其他页面中使用此功能,更具体地说,我正在尝试将此功能添加到我的wordpress网站,该网站位于:root/wp在我的wordpress标题中,我包括client.php:

include "../dir/includes/client.php";

我得到了输出,所以我确信它被包括在内,但是,当我打开wordpress(root/wp)时,我的全局变量都不起作用,结果是$available = null,而它应该是"false",因为它在client.php 中定义

令人困惑的是,当我在wordpress标头中回显$available时,我可以获得值,但当我在client.php中回显时,它再次为null,所以如果我在wordpress标头和client.php中都回显,当我打开wordpress页面时,我会看到标头中包含的那个,而client.php中的另一个为null。

任何帮助都将不胜感激。

这可能是变量范围的问题。尝试使用

$GLOBALS['available']

而不是

$available

在你的client.php中。所以它将在全局范围内定义。在定义部分:

$GLOBALS['available'] = "false"; and $GLOBALS['available'] = "true";

您的问题可能是包含文件中的链接引用。您可以尝试:include "/rootfolder/dir/includes/client.php";而不是包括"../dir/includes/client.php";也有这样的问题,但这解决了它。