And*_*nna -1 php zend-framework
我有以下问题: -
//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
?>
Run Code Online (Sandbox Code Playgroud)
当我尝试访问common.inc.php中的全局变量$ settings时,即使我在setting.inc.php中设置变量,它也会设置为null.如果我调试,当我退出setting.inc.php时,$ settings valiable在index.php中设置,但是当我进入common.inc.php时,$ settings valiable被设置为null.
有没有人有任何想法?
答:在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()
}
Run Code Online (Sandbox Code Playgroud)
更多信息:
如果您想了解何时使用global
以及何时不使用的更多信息,请查看有关变量范围的php.net文档.