php中static關(guān)鍵字的作用是:1、放在函數(shù)內(nèi)部修飾變量,函數(shù)執(zhí)行完后變量值仍然保存;2、放在類(lèi)中修飾屬性或方法,如果修飾的是類(lèi)的屬性,則保留值;3、放在類(lèi)的方法中修飾變量;4、修飾全局作用域的變量。
static關(guān)鍵字的作用如下:
1、放在函數(shù)內(nèi)部修飾變量;
2、放在類(lèi)里修飾屬性或方法;
3、放在類(lèi)的方法里修飾變量;
4、修飾全局作用域的變量;
關(guān)鍵字所表示的不同含義如下:
1、在函數(shù)執(zhí)行完后,變量值仍然保存
如下所示:
<?php function testStatic() { static $val = 1; echo $val; $val++; } testStatic(); //output 1 testStatic(); //output 2 testStatic(); //output 3 ?>
2、修飾屬性或方法,可以通過(guò)類(lèi)名訪問(wèn),如果是修飾的是類(lèi)的屬性,保留值
如下所示:
<?php class Person { static $id = 0; function __construct() { self::$id++; } static function getId() { return self::$id; } } echo Person::$id; //output 0 echo "<br/>"; $p1=new Person(); $p2=new Person(); $p3=new Person(); echo Person::$id; //output 3 ?>
3、修飾類(lèi)的方法里面的變量
如下所示:
<?php class Person { static function tellAge() { static $age = 0; $age++; echo "The age is: $age "; } } echo Person::tellAge(); //output 'The age is: 1' echo Person::tellAge(); //output 'The age is: 2' echo Person::tellAge(); //output 'The age is: 3' echo Person::tellAge(); //output 'The age is: 4' ?>
4、修飾全局作用域的變量,沒(méi)有實(shí)際意義
如下所示:
<?php static $name = 1; $name++; echo $name; ?> 另外:考慮到PHP變量作用域 <?php include 'ChromePhp.php'; $age=0; $age++; function test1() { static $age = 100; $age++; ChromePhp::log($age); //output 101 } function test2() { static $age = 1000; $age++; ChromePhp::log($age); //output 1001 } test1(); test2(); ChromePhp::log($age); //outpuut 1 ?>
可以看出,這3個(gè)變量是不相互影響的。另外,PHP里面只有全局作用域和函數(shù)作用域,沒(méi)有塊作用域。
如果您想學(xué)習(xí)