Home >Backend Development >PHP Tutorial >Study, research and analysis of static keyword principle in PHP_PHP tutorial

Study, research and analysis of static keyword principle in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:26:33758browse

看PHP手册的时候发现了下面这样一段代码:

复制代码 代码如下:

function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test();
}
$count--;
}
?>

执行结果如下:
这是一个递归的函数,声明的静态变量count记录次数,输出1~10。
我在看的时候有个疑惑,递归调用的时候 static $count = 0; 语句会重复执行,这为什么不会导致count变量被重复赋值呢?带着这个疑问和同事研究了一下,测试用代码如下:
复制代码 代码如下:

echo 'start
';
static $a = 10;
echo "$a
";
unset($GLOBALS['a']);
echo "$a
";
static $a = 20;
echo "$a
";
$GLOBALS['a'] = 10;
echo "$a
";
static $a = 30;
echo "$a
";
unset($GLOBALS['a']);
echo "$a
";
static $a;
echo "$a
";
static $a = 40;
echo "$a
";
$a = 100;
echo "$a
";
static $a = 50;
echo "$a
";
static $a = 4;
echo "$a
";
echo 'end
';
exit;
?>

执行结果如下:
start
  1. Notice: Undefined variable: a 
  2. 10 
  3. 10 
  4. Notice: Undefined variable: a 
  5. 10 
  6. 10 
  7. 100 
  8. 100 
  9. 100 
  10. end
(结果中关于文件位置的部分已删去。也可以去掉echo语句使用zend的debug功能查看,这样结果更清晰)

代码第5行第一次输出$a的值为4,由此推测PHP在页面初始化的时候分配静态变量的内存,此时使用了同一个变量的最后一次声明的值(这个可以把4改为其他数测试)。代码第7行调用unset函数销毁变量$a,再次输出$a的值时看到未定义变量的提示,说明变量已经被销毁。

When line 10 is output again, the output result is still 4 instead of 20. There are two possibilities. One is that PHP initializes the value of $a again, and the other is that PHP uses $a before it is destroyed. value, this problem is solved when outputting on line 20. The value of $a is 10 when it is destroyed in line 16, and the output is still 10 after it is declared in line 19.

Change the value of $a to 10 on line 11, declare $a again on line 14, and output it as 10 on line 17. It is speculated that when the declaration is repeated, PHP still uses the value in the static variable memory without assigning it again.

At this point, the problem found in the manual has been roughly solved, that is, the statement in the recursive call did not change the value of $count, so the recursion stopped successfully when $count=10.

There may be some incorrect understandings, please comment.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323948.htmlTechArticleWhen I was reading the PHP manual, I found the following code: Copy the code as follows: ?php function Test() { static $count = 0; $count++; echo $count; if ($count 10) { Test(); } $cou...
Statement:
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