在PHP中访问全局变量的问题

前端之家收集整理的这篇文章主要介绍了在PHP中访问全局变量的问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下是代码段:
  1. function something() {
  2. $include_file = 'test.PHP';
  3. if ( file_exists($include_file) ) {
  4. require_once ($include_file);
  5. // global $flag;
  6. // echo 'in main global scope flag='.$flag;
  7. test();
  8. }
  9. }
  10.  
  11. something();
  12.  
  13. exit;
  14.  
  15. //in test.PHP
  16.  
  17. $flag = 4;
  18. function test() {
  19. global $flag;
  20.  
  21. echo '<br/>in test flag="'.$flag.'"';
  22. if ($flag) {
  23. echo 'flag works';
  24. //do something
  25. }
  26. }

上面的代码片段正确地回应了’全局范围’$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.

– 适用于includePHP手册页,也适用于include_once,require和require_once

我要猜测你得到的错误是在if($flag)行上,因为在那一点上,$flag是未初始化的,因为全局$flag变量从未被赋值.

顺便说一下,echo’global scope flag =’.$flag;也没有显示全局标志,因为你需要一个全局$flag;在该函数显示全局副本,这也具有使$flag = 4的副作用;影响包含文件中的全局副本.

猜你在找的PHP相关文章