我对以下内容有问题:-
//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 中访问全局变量$settings时.php即使我在 set.inc.php 中设置了变量,它也设置为 null。如果我调试,当我退出 set.inc 时.php可用$settings设置在索引.php中,但是当我步入 common.inc 时.php可用$settings设置为 null。
有人有什么想法吗?
答:在inc/common.inc.php
文件中,您不需要使用 global
关键字,该变量已经可以访问。使用 global
重新定义变量,因此null
。
解释:
变量范围是这里的关键。仅当范围更改时,才需要 global
关键字。常规文件(包括 include()
s(的作用域都是相同的,因此同一范围内的任何 php 都可以访问所有变量,即使它来自不同的文件。
您需要在何处使用 global
的示例是在函数内部。函数的作用域与普通 php 的作用域不同,普通 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 文档。