什么是静态变量?
静态变量 类型说明符是static。
静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存储空间(在程序整个运行期间都不释放),也可以认为是其内存地址不变,直到整个程序运行结束。
静态变量虽在程序的整个执行过程中始终存在,但是在它作用域之外不能使用。
只要在变量前加上关键字static,该变量就成为静态变量了。
php静态变量的作用
1、在函数内部修饰变量。静态变量在函数被调用的过程中其值维持不变。<?php
function testStatic() {
static $val = 1;
echo $val."
";;
$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 "
";
$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
更多PHP相关知识,请访问php中文网!