靜態變量只存在於函數作用域內,也就是說,靜態變量只存活在棧中。一般的函數內變量在函數結束後會釋放,比如局部變量,但是靜態變量卻不會。就是說,下次再調用這個函數的時候,該變量的值會保留下來。
只要在變量前加上關鍵字static,該變量就成為靜態變量了。
<?php
function test()
{
static $nm = 1;
$nm = $nm * 2;
print $nm."<br />";
}
// 第一次執行,$nm = 2
test();
// 第一次執行,$nm = 4
test();
// 第一次執行,$nm = 8
test();
?>
程序運行結果:
2 4 8
函數test()執行後,變量$nm的值都保存了下來了。
在class中經常使用到靜態屬性,比如靜態成員、靜態方法。
靜態變量$nm屬於類bkjia,而不屬於類的某個實例。這個變量對所有實例都有效。
::是作用域限定操作符,這裡用的是self作用域,而不是$this作用域,$this作用域只表示類的當前實例,self::表示的是類本身。
<?php
class bkjia
{
public static $nm = 1;
function nmMethod()
{
self::$nm += 2;
echo self::$nm . '<br />';
}
}
$nmInstance1 = new bkjia();
$nmInstance1 -> nmMethod();
$nmInstance2 = new bkjia();
$nmInstance2 -> nmMethod();
?>
程序運行結果:
3 5
<?php
class NowaMagic
{
public static $nm = 'www.bkjia.com';
public function nmMethod()
{
return self::$nm;
}
}
class Article extends NowaMagic
{
public function articleMethod()
{
return parent::$nm;
}
}
// 通過作用於限定操作符訪問靜態變量
print NowaMagic::$nm . "<br />";
// 調用類的方法
$bkjia = new NowaMagic();
print $bkjia->nmMethod() . "<br />";
print Article::$nm . "<br />";
$nmArticle = new Article();
print $nmArticle->nmMethod() . "<br />";
?>
程序運行結果:
www.bkjia.com www.bkjia.com www.bkjia.com www.bkjia.com
PHP沒有靜態構造器,你可能需要初始化靜態類,有一個很簡單的方法,在類定義後面直接調用類的Demonstration()方法。
<?php
function Demonstration()
{
return 'This is the result of demonstration()';
}
class MyStaticClass
{
//public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
public static $MyStaticVar = null;
public static function MyStaticInit()
{
//this is the static constructor
//because in a function, everything is allowed, including initializing using other functions
self::$MyStaticVar = Demonstration();
}
} MyStaticClass::MyStaticInit(); //Call the static constructor
echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
程序運行結果:
This is the result of demonstration()