php 函數中使用static變數_PHP教程

來源:互聯網
上載者:User
本文章來簡單的介紹一下關於static變數在php函數中的用法,有需要瞭解的同學可參考一下。
代碼如下 複製代碼

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只能作用於此函數。

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

代碼如下 複製代碼
class test
{
public static function a(){}
public function b(){}
}
$obj = new test;

調用 代碼

代碼如下 複製代碼

test::a();
$obj->a();
$obj->b();

變數範圍的另一個重要特性是靜態變數(static variable)。靜態變數僅在局部函數域中存在,但當程式執行離開此範圍時,其值並不丟失

例子 使用靜態變數的例子

代碼如下 複製代碼
function test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>

現在,每次調用 test() 函數都會輸出 $w3sky 的值並加一。


更多詳細內容請查看:http://www.bKjia.c0m/phper/php/php-static.htm

http://www.bkjia.com/PHPjc/629126.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/629126.htmlTechArticle本文章來簡單的介紹一下關於static變數在php函數中的用法,有需要瞭解的同學可參考一下。 代碼如下 複製代碼 function sendHeader($num, $rtarr =...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.