【PHP学习笔记】static用法探究

在看别人项目过程中,看到函数里面很多static修饰的变量,关于static修饰的变量,作用域,用法越看越困惑。所以查了下资料。

static用法如下:

1.static 放在函数内部修饰变量

2.static放在类里修饰属性,或方法

3.static放在类的方法里修饰变量

4.static修饰在全局作用域的变量

所表示的不同含义如下:

1.在函数执行完后,变量值仍然保存

 1 <?php
2 function testStatic(){
3 static $val=1;
4 echo $val;
5 $val++;
6 }
7 testStatic();
8 testStatic();
9 testStatic();
10 ?>

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

 1 <?php
2 class Person {
3 static $id = 0;
4
5 function __construct(){
6 self::$id++;
7 }
8
9 static function getId(){
10 return self::$id;
11 }
12 }
13 echo Person::$id;//output 0
14 echo "<br/>";
15
16 $p1=new Person();
17 $p2=new Person();
18 $p3=new Person();
19
20 echo Person::$id;//output 3
21 ?>

3.修饰类的方法里面的变量

 1 <?php
2 class Person {
3 static function tellAge() {
4 static $age = 0;
5 $age++;
6 echo "The age is: $age\n";
7 }
8 }
9 echo Person::tellAge();//output 'The age is: 1'
10 echo Person::tellAge();//output 'The age is: 2'
11 echo Person::tellAge();//output 'The age is: 3'
12 echo Person::tellAge();//output 'The age is: 4'
13 ?>

4.修饰全局作用域的变量,没有实际意义

1 <?php
2 static $name=1;
3 $name++;
4 echo $name;
5 ?>

另外:考虑到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个变量是不相互影响的(PHP里面只有全局作用域和函数作用域,没有块作用域)

<?php
include 'ChromePhp.php';
$age=0;
$age++;
for($i=0;$i<10;$i++){
$age++;
}
ChromePhp::log($i);//output 10;
ChromePhp::log($age);//output 11;
?>

参考资料:PHP: static variable in function, class, method

Static Keyword

     Variable scope  

     Variables