PHP访问require()函数的变量问题

时间:2011-08-28 10:53:36

标签: php

我对PHP require()函数有疑问。我有一个名为(login.php)的PHP脚本,并在其上(login.php)我使用各种require()函数来获取繁重的PHP编码脚本来处理原始脚本(login.php)。

但是我在require()脚本上注意到我可以访问原始(login.php)上定义的局部变量。但问题是在所需的脚本上我有另一个require()函数,那么最初在(login.php)上定义的那些变量会丢失(即如果我执行isset()表示它们没有设置? )。那么如何在require()问题内解决这个require()

任何想法可能改为使用$_SESSION$GLOBALS变量?我知道$_SESSION变量,但$GLOBALS变量是否安全?

以下是(login.php)

上脚本var设置的简短示例
if(!isset($header_displayed))
    {
        echo "<div id='header'>
            <div id='logo'></div>
        </div>";
        $header_displayed=1; 
    }

然后使用require()

从上面(login.php)调用此脚本
if(!function_exists('writeErrors'))
    {
        function writeErrors($error,$host_details,$date,$page,$line) 
        {
            require("/home/darren/crash_msg/error_msg.php");
        }
    }

然后在error_msg上调用了$ header_displayed var的脚本?

从反馈看来,在函数中使用require()会限制所有的全局变量。所以你必须这样做:

    if(!function_exists('writeErrors'))
    {
        function writeErrors($error,$host_details,$date,$page,$line, add var paramters that you need ie $header_displayed) 
        {
            /*log SQL stuff*/
            $display_error_msg=1;
require("/home/darren/crash_msg/error_msg.php"); /*now header_displayed var set on this script*/
        }
    }

3 个答案:

答案 0 :(得分:6)

根据您的评论,您在函数内部调用require()。这就是你的问题所在。当你在函数中包含/ require时,包含的脚本会继承该函数的范围,该范围不包括login.php脚本或login.php包含的第一个脚本中定义的全局变量。

最好使用全局变量来将它们称为$GLOBALS['varname']。请注意,它不是$_GLOBAL,而是它自己独特的怪异性。

关于安全性,只要关闭$GLOBALS(并且它确实应该是这样),使用register_globals的安全性就不会低于其他任何安全性。过分依赖全局变量,特别是在其他脚本中定义的全局变量上,这被认为是一种草率的做法。

通常最好只将所需的值作为参数传递给函数,或者存储您知道在$_SESSION中一直需要的变量。

不建议在函数内部调用包含文件,因为在单独读取包含文件时,它没有运行范围的上下文。您可以假设它在全局范围内执行,但这是不正确的。在任何可能的程度上,建议重构代码以避免包含在函数内部。例如,在包含的文件中执行的任何内容都应该包含在一个函数中,并将所需的全局变量作为参数传递给它。将该函数称为require()

答案 1 :(得分:0)

包含的页面变量属于这些变量的范围,因此请考虑以下a.php,b.php和c.php:

a.php只会

$a = "a"; //This is a global variable, it will be avaliable in all files
include("b.php");
echo "A: \n"
var_dump($a, $b, $c);

b.php

$b = "b"; //This variable is also considered global, as it is scoped to the first, main document.
include("c.php");
echo "B: \n";
var_dump($a, $b, $c);

c.php

$c = "c"; //This variable will only show on b.php and c.php, it is scoped to b.php and its dependencies.
echo "C: \n";
var_dump($a, $b, $c);

以上将输出:

C:
(all variables)

B:
(all variables)

A:
(only A and B)

<强> See this link on ways to solve this issue.

答案 2 :(得分:0)

require()与变量可见性无关(至少只要你包含文件) 所有变量范围问题都属于函数使用。 http://www.php.net/manual/en/language.variables.scope.php