视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
php中static关键字的作用是什么
2020-11-02 18:48:48 责编:小采
文档

static关键字的作用如下:

1、放在函数内部修饰变量;

2、放在类里修饰属性或方法;

3、放在类的方法里修饰变量;

4、修饰全局作用域的变量;

关键字所表示的不同含义如下:

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里面只有全局作用域和函数作用域,没有块作用域。

如果您想学习更多相关知识,欢迎访问gxlcms。

下载本文
显示全文
专题