如何在
PHP函数中获取当前的递归级别?我的意思是,有这样的“神奇”(或最终正常)功能:
- function doSomething($things) {
- if (is_array($things)) {
- foreach ($things as $thing) {
- doSomething($thing);
- }
- } else {
- // This is what I want :
- echo current_recursion_level();
- }
- }
我知道我可以使用另一个函数参数(在此示例中为$level):
- function doSomething($things,$level = 0) {
- if (is_array($things)) {
- foreach ($things as $thing) {
- $level++;
- doSomething($thing,$level);
- }
- } else {
- echo $level;
- }
- }
但我想知道是否有内置函数(或技巧)来做到这一点.也许有一些与debug_backtrace(),但它似乎不是一个简单或快速的解决方案.
我没有找到这个信息,也许它根本就不存在……
如果你只是想避免达到PHP的100级递归限制那么
- count(debug_backtrace());
应该足够了.否则你没有选择传递深度参数,尽管precrement运算符使它更清晰,如下例所示.
- function recursable ( $depth = 0 ) {
- if ($depth > 3) {
- debug_print_backtrace();
- return true;
- } else {
- return recursable( ++$depth );
- }
- }