PHP 全局变量_PHP教程
程序员文章站
2022-05-17 15:58:47
...
= "why" = "what"changeName();
"my name is " . . "
"?>
执行代码的结果是:my name is why,而不是执行changeName()后显示what。分析原因,这是因为函数体changeName内$name变量被缺省设置为局部变量,$name的作用域就是在changeName内。于是,修改代码,添加全局变量如下:
= "why" = "what"changeName();
"my name is " . . "
"?>
注意:
定义全局变量后执行的结果仍然为my name is why,这个结果让我吃惊。原来," 也就是说,当一个函数引用一个外部变量时,可以在函数内通过global来声明该变量,这样该变量就可以在函数中使用了(相当于当作参数传递进来)。那么,再次修改代码:
= "why" = "what" "my name is " . . "
"?>
这次的运行结果是:my name is what,说明
= "why" = "what" = "where" "my name is " . . "
"?>
= "why"['name'] = "what" "my name is " . . "
"?>
= 1 = 2['var2'] = &['var1' . "
" = 1 = 2 , = & . "
"?>
; 就可以访问它们。与所有其他超全局变量不同,$GLOBALS在PHP中总是可用的。另一个例子:
= 1(['var1' . "
" = 1 ( ?>