Home >php教程 >php手册 >php函数中使用static

php函数中使用static

WBOY
WBOYOriginal
2016-06-13 10:49:541103browse

function sendHeader($num, $rtarr = null) {
    static $sapi = null;
    if ($sapi === null) {
        $sapi = php_sapi_name();
    }
    return $sapi++;
  看PW源码的时候发现setHeader()函数中使用static关键字,很奇怪,以前也没这样用过。
static用在函数里面,声明一次变量后,如果再次调用这个函数将会在初始值延续,如$sapi这里将累加。

echo sendHeader(1)."
";
echo sendHeader(2)."
";
echo sendHeader(3)."
";
  output:

apache2handler
apache2handles
apache2handlet
  和global有点类似,但不同的是作用域。static只能作用于此函数。
有点意思。需要深入研究。

 

 

摘自 zaric

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn