php设置 公共变量_PHP: 变量范围 - Manual

In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

error_reporting(E_ALL);$GLOB=0;

functiontest_references() {

global$GLOB;// get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB$test=1;// declare some local var$GLOBALS['GLOB'] = &$test;// make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test$GLOB=2;// set new value to global variable via earlier set local representation, write to old addressecho"Value of global variable (via local representation set by keyword global):$GLOB


";// check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)echo"Value of global variable (via superglobal array GLOBALS):$GLOBALS[GLOB]
";// check global variable using superglobal array => 1 (got value of local variable $test, new address was used)echo"Value ol local variable \$test:$test
";// check local variable that was linked with global using superglobal array => 1 (its value was not affected)global$GLOB;// update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $testecho"Value of global variable (via updated local representation set by keyword global):$GLOB
";// check global variable via local representation => 1 (also value of local variable $test, new address was used)}test_references();

echo"Value of global variable outside of function:$GLOB


";// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值