统计一个递归函数被调用的次数 [英] counting the number of times a recursive function is called
问题描述
我需要知道在函数内调用了多少次递归函数。这是我的功能:
$ p $ 函数结构($ x){
$ qry = mysql_query(SELECT`parent_id` FROM`categories` WHERE`categories_id` = $ x);
$ result = mysql_fetch_assoc($ qry);
$ cat = $ result ['parent_id'];
if($ cat!= 0){
structure($ cat);
}
echo $ cat。'>';
}
我尝试添加计数器,例如$ i = 0,然后是$ i ++,但是每次函数调用时它都会回到$ i = 0。我曾尝试添加数组,并对数组进行计数,但是当每次调用该函数时,它都必须设置一个新数组$ i = array()。
我能想到的一种方法可能是,如果我在函数外设置数组或计数器,但我不知道是否可以调用一个变量一个函数在函数之外。
关于如何在函数外部调用变量或甚至更好地计算函数被调用的次数的想法?选项1:通过引用传入变量
解决方案
函数结构($ cat,& $ counter){
$ counter ++;
...
}
结构('foo',$ counter);
echo $ counter;
选项2:使用 static
变量
函数结构($ cat){
static $ counter = 0;
echo ++ $ counter;
...
}
选项3:使用 global
variable(no no!)
$ counter = 0;
函数结构($ cat){
global $ counter;
$ counter ++;
...
}
选项4:使用闭包
$ counter = 0;
$ structure = function($ cat)use(& $ counter){
$ counter ++;
...
}
$结构('foo');
echo $ counter;
I need to know how many times a recursive function is called within the function. This is my function:
function structure($x) {
$qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x");
$result = mysql_fetch_assoc($qry);
$cat = $result['parent_id'];
if($cat !=0) {
structure($cat);
}
echo $cat.' >';
}
I have tried adding a counter, e.g. $i=0, then $i++, but it will of course revert back to the $i=0 every time the function is called. I have tried adding arrays, and counting the arrays, but of course it has to set a new array, $i=array(), every time the function is called.
The one way I can think might work is if I set the array or counter outside of the function, but I don't know if its possible to call a variable in a function that is outside the function.
Any ideas on how to call a variable outside a function or even a better way to count the times the function is called?
Option 1: pass in a variable by reference
function structure($cat, &$counter) {
$counter++;
...
}
structure('foo', $counter);
echo $counter;
Option 2: use a static
variable
function structure($cat) {
static $counter = 0;
echo ++$counter;
...
}
Option 3: use a global
variable (no no!)
$counter = 0;
function structure($cat) {
global $counter;
$counter++;
...
}
Option 4: use a closure
$counter = 0;
$structure = function ($cat) use (&$counter) {
$counter++;
...
}
$structure('foo');
echo $counter;
这篇关于统计一个递归函数被调用的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!