当前位置:首页 > Web开发 > 正文

变量值仍然保存 如下所示: ? phpfunction testStatic() { static $val = 1 ;

2024-03-31 Web开发

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之static静态变量详解

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30692.html