Home > Backend Development > PHP Tutorial > php的函数表达式能递归嘛?

php的函数表达式能递归嘛?

WBOY
Release: 2016-06-06 20:50:03
Original
952 people have browsed it

有一个函数表达式

<code>$make = function($std){};
</code>
Copy after login
Copy after login

如何实现递归?

<code>$make = function($std){ $make($std);  };
</code>
Copy after login
Copy after login

排除这样的写法,不太优雅

<code>$make = function($std, $make){ $make($std);  };
$make($std, $make);
</code>
Copy after login
Copy after login

回复内容:

有一个函数表达式

<code>$make = function($std){};
</code>
Copy after login
Copy after login

如何实现递归?

<code>$make = function($std){ $make($std);  };
</code>
Copy after login
Copy after login

排除这样的写法,不太优雅

<code>$make = function($std, $make){ $make($std);  };
$make($std, $make);
</code>
Copy after login
Copy after login

<code>$f = function($x) use(&$f){
    if($x==0 || $x==1)
        return 1;
    return $f($x-1) + $f($x-2);
};

print $f(10);
</code>
Copy after login

我想楼主要的一定是这种东西。注意,use(&$f)这里必须用引用,否则会出错。

use可以在定义匿名函数时,把外部的变量捕捉(值复制)到匿名函数内部。
在这个例子中,在未完成赋值时,$f可以认为还不存在,这时捕捉的话,所捕捉的是一个未定义的变量。 所以我们要捕捉一个引用,这样在$f赋值完成后,匿名函数内部的$f也就指向匿名函数自身了。
(这话太绕了...)

<code><?php function make($std)
{
        if ($std < 0)
                return -1;

        if(($std == 0) || ($std == 1))
                return $std;

        return make($std - 1) + make($std - 2);
}

for ($i = 1; $i < 20; ++$i){
        echo make($i);
        echo " ";
}
?>
</code>
Copy after login

这个斐波那契的递归计算给你做个参考哈。

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