Home >Backend Development >PHP Tutorial >php recursive parsing

php recursive parsing

WBOY
WBOYOriginal
2016-08-08 09:24:121356browse
<span style="font-family: Arial, Helvetica, sans-serif;"></span>
function test($i){//第一步
	$i  -= 4; 
	if($i<3){ 
		return $i; //第二部
	}else{ 
		test($i); //第三部
	} 
} 
echo test(10); 
function test($i){//第一步
<span style="white-space:pre">	</span>$i  -= 4; 
<span style="white-space:pre">	</span>if($i<3){ 
<span style="white-space:pre">		</span>return $i; //第二步
<span style="white-space:pre">	</span>}else{ 
<span style="white-space:pre">		</span>function test($i){//第 3步
<span style="white-space:pre">			</span>$i  -= 4; 
<span style="white-space:pre">			</span>if($i<3){ 
<span style="white-space:pre">				</span>return $i; //第4步
<span style="white-space:pre">			</span>}else{ 
<span style="white-space:pre">				</span>test();//第5步
<span style="white-space:pre">			</span>} 
<span style="white-space:pre">		</span>} 
<span style="white-space:pre">	</span>} 
} 
echo test(30); 




上面的的第一段代码作为例子<p>写这样代码的人可以没完全理解递推,</p><p>下面使用test(10)调用,在执行过程中,如果条件成立,则直接返回结果,</p><p>如果条件不成立则继续调用test(),猛一看这样写没问题,其实,当第一次调用条件不成立时再调用一次时,即使成立也没用返回值,第二段代码是两次调的结果:</p><p>假如在第二次调用,代码执行到第四步时结果成立,他的动作是return 2;  现在代码成什么样子了呢,看下面
function test($i){//第一步
	$i  -= 4; 
	if($i<3){ 
		return $i; //第二部
	}else{ 
		2;
	} 
} 
echo test(10); 

There is only a single 2. How does it return to the bottom? A return must be added in front;

So the complete code should be like this.

function test($i){//第一步
	$i  -= 4; 
	if($i<3){ 
		return $i; //第二部
	}else{ 
		return test($i);
	} 
} 
echo test(10); 

The above has introduced PHP recursive parsing, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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