PHP的静态变量介绍
来源:互联网 发布:网络校时电话 编辑:程序博客网 时间:2024/06/04 18:18
静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。
只要在变量前加上关键字static,该变量就成为静态变量了。
01
<?php
02
function
test()
03
{
04
static
$nm
= 1;
05
$nm
=
$nm
* 2;
06
print
$nm
.
"<br />"
;
07
}
08
09
// 第一次执行,$nm = 2
10
test();
11
// 第一次执行,$nm = 4
12
test();
13
// 第一次执行,$nm = 8
14
test();
15
?>
程序运行结果:
1
2
2
4
3
8
函数test()执行后,变量$nm的值都保存了下来了。
在class中经常使用到静态属性,比如静态成员、静态方法。
Program List:类的静态成员
静态变量$nm属于类nowamagic,而不属于类的某个实例。这个变量对所有实例都有效。
::是作用域限定操作符,这里用的是self作用域,而不是$this作用域,$this作用域只表示类的当前实例,self::表示的是类本身。
01
<?php
02
class
nowamagic
03
{
04
public
static
$nm
= 1;
05
06
function
nmMethod()
07
{
08
self::
$nm
+= 2;
09
echo
self::
$nm
.
'<br />'
;
10
}
11
}
12
13
$nmInstance1
=
new
nowamagic();
14
$nmInstance1
-> nmMethod();
15
16
$nmInstance2
=
new
nowamagic();
17
$nmInstance2
-> nmMethod();
18
?>
程序运行结果:
1
3
2
5
Program List:静态属性
01
<?php
02
class
NowaMagic
03
{
04
public
static
$nm
=
'www.nowamagic.net'
;
05
06
public
function
nmMethod()
07
{
08
return
self::
$nm
;
09
}
10
}
11
12
class
Article
extends
NowaMagic
13
{
14
public
function
articleMethod()
15
{
16
return
parent::
$nm
;
17
}
18
}
19
20
// 通过作用于限定操作符访问静态变量
21
print NowaMagic::
$nm
.
"<br />"
;
22
23
// 调用类的方法
24
$nowamagic
=
new
NowaMagic();
25
print
$nowamagic
->nmMethod() .
"<br />"
;
26
27
print Article::
$nm
.
"<br />"
;
28
29
$nmArticle
=
new
Article();
30
print
$nmArticle
->nmMethod() .
"<br />"
;
31
?>
程序运行结果:
1
www.nowamagic.net
2
www.nowamagic.net
3
www.nowamagic.net
4
www.nowamagic.net
Program List:简单的静态构造器
PHP没有静态构造器,你可能需要初始化静态类,有一个很简单的方法,在类定义后面直接调用类的Demonstration()方法。
01
<?php
02
function
Demonstration()
03
{
04
return
'This is the result of demonstration()'
;
05
}
06
07
class
MyStaticClass
08
{
09
//public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
10
public
static
$MyStaticVar
= null;
11
12
public
static
function
MyStaticInit()
13
{
14
//this is the static constructor
15
//because in a function, everything is allowed, including initializing using other functions
16
17
self::
$MyStaticVar
= Demonstration();
18
}
19
} MyStaticClass::MyStaticInit();
//Call the static constructor
20
21
echo
MyStaticClass::
$MyStaticVar
;
22
//This is the result of demonstration()
23
?>
程序运行结果:
1
This is the result of demonstration()
转http://www.nowamagic.net/php/php_StaticVariable.php
0 0
- PHP的静态变量介绍
- PHP的静态变量介绍
- PHP的静态变量介绍
- PHP的静态变量介绍
- PHP的静态变量
- php中static静态变量的用法介绍
- php静态变量的妙用
- PHP的静态变量管理
- PHP 静态变量的使用
- PHP的静态方法介绍
- 关于静态变量的的介绍
- Android静态变量的生命周期 简单介绍
- Android静态变量的生命周期 简单介绍
- Android静态变量的生命周期 简单介绍
- 关于php类静态变量的例子
- 关于PHP的static(静态)变量
- PHP的常量就是静态变量
- PHP 类中的静态变量的继承
- PA 项目创建任务
- KAFKA分布式消息系统
- 我的oracle笔记-05 之 保留空间
- Docker 快速学习
- 两个字符串中最大相同的子串
- PHP的静态变量介绍
- PA 项目任务创建资源
- No curses/termcap library found的解决办法
- /bin/bash^M: 坏的解释器: 没有那个文件或目录
- PA 项目关联项目经理
- VeryCD下载方法
- 模拟一个String的trim功能
- 3.Spring Bean
- 安装FTP服务器