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