加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-25 08:42:30 所属栏目:PHP 来源:互联网
导读:以下是代码段: function something() {$include_file = test.php;if ( file_exists($include_file) ) { require_once ($include_file);// global $flag;// echo in main global scope flag=.$flag

以下是代码段:

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的副作用;影响包含文件中的全局副本.

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读