
什么是静态变量?
静态变量 类型说明符是static。
静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存储空间(在程序整个运行期间都不释放),也可以认为是其内存地址不变,直到整个程序运行结束。
静态变量虽在程序的整个执行过程中始终存在,但是在它作用域之外不能使用。
立即学习“PHP免费学习笔记(深入)”;
只要在变量前加上关键字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
更多PHP相关知识,请访问php中文网!
以上就是php静态变量的作用是什么?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号