您好,欢迎访问一九零五行业门户网

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

什么是静态变量?
静态变量 类型说明符是static。
静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存储空间(在程序整个运行期间都不释放),也可以认为是其内存地址不变,直到整个程序运行结束。
静态变量虽在程序的整个执行过程中始终存在,但是在它作用域之外不能使用。
只要在变量前加上关键字static,该变量就成为静态变量了。
php静态变量的作用
1、在函数内部修饰变量。静态变量在函数被调用的过程中其值维持不变。
<?phpfunction teststatic() { static $val = 1; echo $val."<br />";; $val++;}teststatic(); //output 1teststatic(); //output 2teststatic(); //output 3?>
程序运行结果:
123
2、在类里修饰属性,或方法。
修饰属性或方法,可以通过类名访问,如果是修饰的是类的属性,保留值
<?phpclass person { static $id = 0; function __construct() { self::$id++; } static function getid() { return self::$id; }}echo person::$id; //output 0echo "<br/>"; $p1=new person();$p2=new person();$p3=new person(); echo person::$id; //output 3?>
程序运行结果:
03
3、在类的方法里修饰变量。
<?phpclass 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静态变量的作用是什么?的详细内容。
其它类似信息

推荐信息