<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->1<?php
2$var=0;
3functiontest($index)
4{
5$var=$var+1;
6echo"The".$index."numberis".$var."<br>";
7}
8test(1);
9test(2)
10?>
你认为以上的代码会显示什么结果呢?
如果你认为是下面:
结果1:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->The1numberis1
The2numberis 2
不好意思,你的结果是错误的。
其实正确的结果应该是:
结果2
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->The1numberis1
The2numberis1
那么你从其中发现了什么呢?我们可以知道虽然第2行的代码定义在外面,但第5行的变量和它是不一样的。第5行的变量仅在这个函数里使用。进一步的,如果我想调用第一行的变量而显示结果2.代码可以如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->1<?php
2$var=0;
3functiontest($index)
4{
5global$var;
6$var=$var+1;
7echo"The".$index."numberis".$var."<br>";
8}
9test(1);
10test(2)
11?>
这个代码段和上面的代码段有何区别呢?注意第5行,多了一个global关键字。明白了吧。
那么还有没有其他方法呢?答案是肯定的。
代码如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->1<?php
2$var=0;
3functiontest($index)
4{
5
6$GLOBALS["var"]=$GLOBALS["var"]+1;
7echo"The".$index."numberis".$GLOBALS["var"]."<br>";
8}
9test(1);
10test(2)
11?>
代码有什么特殊的吗?那就是用到了$GLOBALS这个超全局变量。
PHP也有静态变量的说法。不过静态变量一般用在函数里,只能是局部变量了。看看下面代码吧:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->1<?php
2functionTest()
3{
4static$a=0;
5echo$a."<br>";
6$a++;
7}
8Test();
9Test();
10?>
结果为
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->1
2