我遇到以下问题: -
//index.php
<?php
define('PATH','Ajfit/');
/* Get all the required files and functions */
require(PATH . 'settings.inc.php');
require(PATH . 'inc/common.inc.php');
?>
//setting.inc.php
<?php
$settings['language']='English';
?>
//inc/common.inc.php
<?php
//global $settings, $lang, $_SESSION; //$setting = null????
$language = $settings['language']; //$language is still null
?>
当我尝试访问common.inc.php中的全局变量$ settings时,即使我在setting.inc.php中设置变量,它也会设置为null。如果我调试,当我退出setting.inc.php时,$ settings valiable在index.php中设置,但是当我进入common.inc.php时,$ settings valiable被设置为null。
有没有人有任何想法?
答案 0 :(得分:5)
答案:在inc/common.inc.php
文件中,您无需使用global
关键字,该变量已可访问。使用global
重新定义变量,因此成为null
。
<强>解释强>
变量范围是此处的关键。只有在范围更改时才需要global
关键字。常规文件(包括include()
s)的范围都是相同的,因此所有变量都可以被同一范围内的任何php访问,即使它来自不同的文件。
您需要使用global
的示例位于函数内部。函数的范围不同于普通php的范围,它与class
范围不同,依此类推。
示例:强>
//foo.php
$foo = "bar";
echo $foo; //prints "bar" since scope hasn't changed.
function zoo() {
echo $foo; //prints "" because of scope change.
}
function zoo2() {
global $foo;
echo $foo; //prints "bar" because $foo is recognized as in a higher scope.
}
include('bar.php');
//bar.php
echo $foo; //prints "bar" because scope still hasn't changed.
function zoo3() {
echo $foo; //prints "" for the same reason as in zoo()
}
function zoo4() {
global $foo;
echo $foo; //prints "bar" for the same reason as in zoo2()
}
更多信息:
如果您想了解何时使用global
以及何时不使用的更多信息,请查看php.net documentation on variable scope。