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

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

*/

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。