Home > Backend Development > PHP Tutorial > php 函数中使用static的说明_PHP

php 函数中使用static的说明_PHP

WBOY
Release: 2016-06-01 12:11:28
Original
833 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只能作用于此函数。

有点意思。需要深入研究。

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template