PHP之static静态变量详解(二)

在看别人项目过程中,看到函数里面很多static修饰的变量,关于static修饰的变量,作用域,用法越看越困惑,所以查了下资料。

static用法如下:

1.static 放在函数内部修饰变量

2.static放在类里修饰属性,或方法

3.static放在类的方法里修饰变量

4.static修饰在全局作用域的变量

所表示的不同含义如下:

1.在函数执行完后,变量值仍然保存

如下所示:


functiontestStatic() {

static$val= 1;

echo$val;

$val++;

}

testStatic();//output 1

testStatic();//output 2

testStatic();//output 3

?>


2.修饰属性或方法,可以通过类名访问,如果是修饰的是类的属性,保留值

如下所示:

classPerson {

static$id= 0;

function__construct() {

self::$id++;

}

staticfunctiongetId() {

returnself::$id;

}

}

echoPerson::$id;//output 0

echo"
";

$p1=newPerson();

$p2=newPerson();

$p3=newPerson();

echoPerson::$id;//output 3

?>


3.修饰类的方法里面的变量

如下所示:


classPerson {

staticfunctiontellAge() {

static$age= 0;

$age++;

echo"The age is:$age

";

}

}

echoPerson::tellAge();//output 'The age is: 1'

echoPerson::tellAge();//output 'The age is: 2'

echoPerson::tellAge();//output 'The age is: 3'

echoPerson::tellAge();//output 'The age is: 4'

?>


4.修饰全局作用域的变量,没有实际意义(存在着作用域的问题,详情查看

如下所示:


static$name= 1;

$name++;

echo$name;

?>

另外:考虑到PHP变量作用域


include'ChromePhp.php';

$age=0;

$age++;

functiontest1() {

static$age= 100;

$age++;

ChromePhp::log($age);//output 101

}

functiontest2() {

static$age= 1000;

$age++;

ChromePhp::log($age);//output 1001

}

test1();

test2();

ChromePhp::log($age);//outpuut 1

?>

可以看出:这3个变量是不相互影响的,另外,PHP里面只有全局作用域和函数作用域,没有块作用域

如下所示:


include'ChromePhp.php';

$age= 0;

$age++;

for($i=0;$i<10;$i++) {

$age++;

}

ChromePhp::log($i);//output 10;

ChromePhp::log($age);//output 11;

?>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,131评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,805评论 18 399
  • 个人学习批处理的初衷来源于实际工作;在某个迭代版本有个BS(安卓手游模拟器)大需求,从而在测试过程中就重复涉及到...
    Luckykailiu阅读 4,814评论 0 11