php 函数中使用static

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)."<br>";
echo sendHeader(2)."<br>";
echo sendHeader(3)."<br>";

  output:

apache2handler
apache2handles
apache2handlet

  和global有点类似,但不同的是作用域。static只能作用于此函数。

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

原文地址:https://www.cnblogs.com/zaric/p/2529061.html