来自其他文件的PHP变量返回为NULL

时间:2009-12-14 17:51:30

标签: php joomla

在一个PHP文件中,我有这段代码:

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一样工作。为什么会发生这种情况?

2 个答案:

答案 0 :(得分: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作为属性。

答案 1 :(得分:0)

我找到了一个似乎有效的解决方案:在最初设置变量时,在我需要使用它之前使用global关键字。

(但这非常麻烦,我仍然不确定为什么会这样,所以如果有人有更好的解决方案,请随时发帖。)

相关问题