static静态变量和类的静态属性和静态方法
看到函数里面很多static修饰的变量,关于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里面只有全局作用域和函数作用域,没有块作用域
如下所示:
<?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 class Human{ static public $name = "小妹"; public $height = 180; static public function tell(){ echo self::$name;//静态方法调用静态属性,使用self关键词 //echo $this->height;//错。静态方法不能调用非静态属性,因为 $this代表实例化对象,而这里是类,不知道 $this 代表哪个对象 } public function say(){ echo self::$name . "我说话了"; //普通方法调用静态属性,同样使用self关键词 echo $this->height; } } $p1 = new Human(); $p1->say(); $p1->tell();//对象可以访问静态方法 echo $p1::$name;//对象访问静态属性。不能这么访问$p1->name,因为静态属性的内存位置不在对象里 Human::say();//错。say()方法有$this时出错;没有$this时能出结果
(1)、静态属性不需要实例化即可调用。因为静态属性存放的位置是在类里,调用方法为"类名::属性名";
(2)、静态方法不需要实例化即可调用。同上
(3)、静态方法不能调用非静态属性。因为非静态属性需要实例化后,存放在对象里;
(4)、静态方法可以调用非静态方法,使用 self 关键词。php里,一个方法被self:: 后,它就自动转变为静态方法;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?