站长资讯网
最全最丰富的资讯网站

php静态变量的作用是什么?

php静态变量的作用是什么?

什么是静态变量?

静态变量 类型说明符是static。

静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存储空间(在程序整个运行期间都不释放),也可以认为是其内存地址不变,直到整个程序运行结束。

静态变量虽在程序的整个执行过程中始终存在,但是在它作用域之外不能使用。

只要在变量前加上关键字static,该变量就成为静态变量了。

php静态变量的作用

1、在函数内部修饰变量。静态变量在函数被调用的过程中其值维持不变。

<?php function testStatic() {     static $val = 1;     echo $val."<br />";;     $val++; } testStatic();   //output 1 testStatic();   //output 2 testStatic();   //output 3 ?>

程序运行结果:

1 2 3

2、在类里修饰属性,或方法。

修饰属性或方法,可以通过类名访问,如果是修饰的是类的属性,保留值

<?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 ?>

程序运行结果:

0 3

3、在类的方法里修饰变量。

<?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' ?>

程序运行结果:

The age is: 1 The age is: 2 The age is: 3 The age is: 4

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号