PHP之static静态变量详解
static用法如下:
1.static 放在函数内部修饰变量
2.static放在类里修饰属性,或方法
3.static放在类的方法里修饰变量
4.static修饰在全局作用域的变量
所表示的不同含义如下:
1.在函数执行完后,变量值仍然保存
如下所示:
<?php function testStatic() { static $val = 1; echo $val; $val++; } testStatic(); //output 1 testStatic(); //output 2 testStatic(); //output 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 ?>
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' ?>
4.修饰全局作用域的变量,没有实际意义(存在着作用域的问题,详情查看)
如下所示:
<?php static $name = 1; $name++; echo $name; ?> 另外:考虑到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里面只有全局作用域和函数作用域,没有块作用域
本文来自博客园,作者:飞龙在生,转载请注明原文链接:https://www.cnblogs.com/flzs/p/12252105.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!