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

php 函数中使用static的说明

WBOY
Release: 2016-06-13 12:00:38
Original
889 people have browsed it

复制代码 代码如下:


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只能作用于此函数。

有点意思。需要深入研究。
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template