以下是代码段:
function something() {
$include_file = 'test.PHP';
if ( file_exists($include_file) ) {
require_once ($include_file);
// global $flag;
// echo 'in main global scope flag='.$flag;
test();
}
}
something();
exit;
//in test.PHP
$flag = 4;
function test() {
global $flag;
echo '<br/>in test flag="'.$flag.'"';
if ($flag) {
echo 'flag works';
//do something
}
}
上面的代码片段正确地回应了’全局范围’$flag值但是没有识别值为4的$flag,假定$flag为null值.
请指出访问该$flag全局变量有什么问题.
提前致谢,
Anitha
$flag = 4;不在全球范围内.
If the include occurs inside a
function within the calling file,then
all of the code contained in the
called file will behave as though it
had been defined inside that function.
– 适用于include的PHP手册页,也适用于include_once,require和require_once
我要猜测你得到的错误是在if($flag)行上,因为在那一点上,$flag是未初始化的,因为全局$flag变量从未被赋值.
顺便说一下,echo’global scope flag =’.$flag;也没有显示全局标志,因为你需要一个全局$flag;在该函数中显示全局副本,这也具有使$flag = 4的副作用;影响包含文件中的全局副本.