PHP 递归函数

递归函数是我们常用到的一类函数,最基本的特点是函数自身调用自身,但必须在调用自身前有条件判断,否则无限无限调用下去。

利用引用做参数

<?php
function test($a=0,&$result=array()){
	$a++;
	if ($a<10) {
	    $result[]=$a;
	    test($a,$result);
	}
	echo $a;
	return $result;
}
print_r(test());
?>

效果图:

 

利用全局变量

<?php
function test($a=0,$result=array()){
    global $result;
    $a++;
    if ($a<10) {
        $result[]=$a;
        test($a,$result);
    }
    return $result;
}
print_r(test());
?>

效果图:

 

利用静态变量

<?php
function test(){
	static $count=0;
	echo $count;
	$count++;
}
test();
test();
test();
test();
test();
?>

效果图:

 

猜你喜欢

转载自onestopweb.iteye.com/blog/2359152