辛星与你解读PHP的递归

WBOY
Release: 2016-06-13 12:03:10
Original
965 people have browsed it

辛星与您解读PHP的递归

     其实递归放到其他编程语言里面可能是初学函数的一个练习题,但是由于PHP的特殊性,我们把它拿出来专门讲解一下,首先说一下什么是递归把,我最早认识递归是求一个数的阶乘,比如我们写一个函数,然后求它的阶乘是多少。

    看下面的PHP代码:

<?php //求n!的值function xin($n){	if($n > 0){		return $n *xin($n -1 );	}else{		return 1;	}}echo xin(4);
Copy after login
 它的输出结果当然是24了,什么意思呢,很简单,我们给xin函数传递一个值,如果它比0大,那么就用它去乘以调用$n-1的xin函数的结果,当然,读者可能有N种方式去计算n的阶乘的计算方式,但是无疑,这是用递归来计算的一种。

     可以看出,PHP中的递归是很类似与高中学习的数学归纳法的,原理非常简单易懂。它的大致步骤就是首先判断是否需要向下递归,如果是的话,给出一个规则,如果不能,需要及时的返回,把控制权交给它的调用者,基本原理就讲这么多了,还有事,先写到这里。


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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!