时间:2021-07-01 10:21:17 帮助过:2人阅读
= "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 " . . "
"?>
结果为:my name is what,如果在changeName2()中添加global $name,运行结果则是:my name is where。
= "why"['name'] = "what" "my name is " . . "
"?>
= 1 = 2['var2'] = &['var1' . "
" = 1 = 2 , = & . "
"?>
输出$var2的值为1,$var4的值为2,因为$var3的引用指向了$var4的引用地址。$var4的实际值并没有改变。官方的解释是:$GLOBALS['var']是外部的全局变量本身,global $var是外部$var的同名引用或者指针。; 就可以访问它们。与所有其他超全局变量不同,$GLOBALS在PHP中总是可用的。另一个例子:
= 1(['var1' . "
" = 1 ( ?>
输出结果是$var1不存在,而$var2的值为1。这就证明,$var2只是别名引用,本身的值没有受到任何的改变。也就是说global $var其实就是$var = &$GLOBALS['var'],调用外部变量的一个别名而已!
http://www.bkjia.com/PHPjc/749824.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/749824.htmlTechArticle? = "why" = "what" changeName(); "my name is " . . "br/" ? 执行代码的结果是:my name is why,而不是执行changeName()后显示what。分析原因,这是因为 函数体...