Home > php教程 > php手册 > PHP中Global和Local范围以及Static变量,globalstatic

PHP中Global和Local范围以及Static变量,globalstatic

WBOY
Release: 2016-06-13 09:11:46
Original
1440 people have browsed it

PHP中Global和Local范围以及Static变量,globalstatic

1. Local scope

function update_counter()

{

  $counter++;//此处$counter为局部变量,与函数外的$counter非同一个

}

$counter = 10;

update_counter();

echo $counter;

//输出:10

 

2. Global scope

function update_counter()

{

  global $counter;//利用global关键字在函数内进行声明即可获取全局域的$counter

  $counter++;

}

$counter = 10;

update_counter();

echo $counter;

//输出: 11

 

function update_counter()

{

  $GLOBALS[counter]++;

}

$counter = 10;

update_counter();

echo $counter;

//输出:11

 

3. Static variables

function update_counter()

{

  static $counter = 0;//利用static关键字进行声明$counter,具有局部域

  $counter++;

echo "Static counter is now $counter\n";

}

$counter = 10;

update_counter();

update_counter();

echo "Global counter is $counter\n";

/*输出:

Static counter is now 1

Static counter is now 2

Global counter is 10

*/

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template