请考虑以下代码:
<?php
function test() {
static $count = 0;
$count++;
echo $count."<br>";
if($count < 2) {
test();
echo "In last line...".$count."<br>";
}
$count--;
echo "Count Value : ".$count."<br>";
}
test();
?>
输出如下:
1
2
Count Value : 1
In last line...1
Count Value : 0
我对以上输出中的以下部分感到困惑,该部分用红色边框勾勒出来。
我想知道如果在成为$count = 2
后返回false,紧接着的代码行echo "Count Value : ".$count."<br>";
就会被执行。然后,它应该停止流动,因为它是最后一个声明。
打印行计数后,为什么程序流程没有停止 价值:1?
那么输出的最后两行是如何生成的?
谁再次调用test()
函数?
静态变量如何再次重置为0并打印输出的最后两行?
答案 0 :(得分:1)
请找到执行...
1.first time calling test()
-> initialized static $count = 0;
-> $count++//$count = 1
-> echo $count."<br>";// output 1
-> if($count < 2) { // here $count is 1 condition passed
2.calling from if statement test()
-> static $count = 0; // as it is static variable will not lose its value when the function exits and will still hold that value should the function be called again // so here $count is 1
-> $count++ //$count = 2
-> echo $count."<br>";// output 2
->if($count < 2) { // here $count is 2 condition failed
-> $count--;$count is 1
-> output Count Value : 1
-> calling from if statement test() is completed.
-> prints next statement "In last line...".$count."<br>";//In last line...1 //value from first time calling test() // output In last line...1
-> $count--;$count is 0
-> Count Value : 0
答案 1 :(得分:0)
<?php
function test()
{
static $count = 0;
$count++;
echo $count."<br>";//first output is 1
if($count < 2) //first time condition true(i.e 1<2) and second time it is false
{
test();
/* here you again calling same function then $count will became 2 and you did not return anything here so next code will get executed after complete of 2nd time function. if you set **return false** here then your marked output does not execute*/
echo "In last line...".$count."<br>";//Here $count will be 1 because its continuing first statement
}
$count--;//first time $count is 2 here but you are decremented here so 1
// second time $count is 1 because continuing first statement and again its decremented so value will became 0.
echo "Count Value : ".$count."<br>";// first output is 1//second output is 0
}
test();
?>
答案 2 :(得分:0)
逐一回答。
1.为什么程序流程在打印行计数值后没有停止:1?
=&GT;因为打印行计数值:1是在函数test()的第二次调用时完成的。
2.那么输出的最后两行是如何生成的?
=&GT;完成第二次通话后,仍然需要完成第一次通话,然后再次开始
echo "In last line...".$count."<br>";
3.谁再次调用test()函数?
=&GT;下面第二行代码片段再次调用函数。
if($count < 2) {
test();
echo "In last line...".$count."<br>";
}
3.静态变量如何再次重置为0并打印输出的最后两行?
=&GT;静态变量不会被重置,静态只会初始化变量一次,一旦启动它就不会打扰这个值。
4.递归时,函数调用执行后的剩余代码执行次数与在测试条件失败时调用递归函数一样多吗?
=&GT;是