2009-12-14 103 views
0

在一个PHP文件,我有这样的代码:PHP变量回来为NULL

require_once $_SERVER['DOCUMENT_ROOT'] . '/custom/functions.php'; 
global $testVar; 
var_dump($testVar); 

functions.php文件,我有这样的开头,后面是一些其他的功能:

function pr($s) { 
    echo '<pre>', htmlspecialchars(print_r($s,true)), '</pre>'; 
} 

$testVar = 'hello world'; 

运行第一个文件时,变量返回为NULL。我添加了global位,但它不应该是必需的。这是Joomla模块的一部分,但我从来没有遇到包括文件在内的问题,它应该像普通的PHP一样工作。为什么会发生这种情况?

+0

是否'function.php'文件以' <?php'? (只是为了确保) – 2009-12-14 17:58:39

+0

只有变量来作为NULL?那功能呢? – GmonC 2009-12-14 18:01:32

+0

当使用PHP 5.2.11进行测试时,该示例生成'string'hello world'(length = 11)'。如果在Joomla模块之外使用它,它是否适用于您? – outis 2009-12-14 18:51:12

回答

1

首先,尝试使用Joomla的路径常量,如JPATH_BASE而不是$_SERVER['DOCUMENT_ROOT']。 Joomla有很多有用的常量,请查看它的文档。

我已阅读您的答案,并阅读PHP文档我试图找到一个原因,为什么你需要使用global关键字两次。

首先,Variable scope

The scope of a variable is the context within which it is defined. For the most 
part all PHP variables only have a single scope. 

(...) 

However, within user-defined functions a local function scope is introduced. 
Any variable used inside a function is by default limited to the local 
function scope. 

该变量不在函数范围内,所以这就是为什么我们认为NULL是一种奇怪的行为。

但后来我读include,发现一些有趣的事情:

(...) 
Any variables available at that line in the calling file will be available 
within the called file, from that point forward. However, all **functions** 
and **classes** defined in the included file have the global scope. 

我看不到关于这些变量是本款全球任何提及。因此,它看起来很麻烦,当你想使用这样的全局变量时,你的解决方案是正确的。

在你的情况下,如果这样做很麻烦,我会创建一个简单的类。如果您的文件中只有助手功能,请使用许多方法创建class Util{},并使用$ testVar作为属性。

+0

如果文件没有找到,你会得到一个致命错误...是错误输出到响应? – asgerhallas 2009-12-14 18:08:01

+0

你说得对,如果$ _SERVER ['DOCUMENT_ROOT']有问题,它甚至不应该回显“NULL”,因为他使用的是require_once而不是include语句。我的错。但JPATH_BASE仍然是一个很好的建议。 – GmonC 2009-12-14 18:20:56

+0

文件包含正常,文件中的功能正常工作。 asgerhallas是对的,如果文件不在那里,它会给出一个错误。不过感谢关于'JPATH_BASE'的提示。 – DisgruntledGoat 2009-12-14 18:52:56

0

我发现了一个似乎可行的解决方案:在最初设置变量时以及在我需要使用它之前,都使用global关键字。

(然而,这是相当麻烦的,我真不知道为什么会发生,因此,如果任何人有一个更好的解决方案,随意张贴。)

+0

我想我对此行为有一个解释。这不是很小,所以我编辑了我自己的答案来解释。你怎么看? – GmonC 2009-12-14 20:05:46