简单的递归函数不起作用

时间:2012-12-18 00:19:15

标签: php function recursion scope

我正在尝试运行递归函数,但它无法正常运行。我的代码中没有看到任何错误,所以也许这对PHP来说是不可能的?

<?php

$herpNum = 0;

function herp() {
    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp();
    }
}

herp();

?>

当我运行它时,结果只是一个很长的列表1.

4 个答案:

答案 0 :(得分:4)

因为$ herpNum与函数的范围不同,所以它在函数内创建一个新的$ herpNum,默认为0,然后加1。

您既可以将其作为争论传递,也可以将其作为全局变量。

$herpNum = 0;

function herp($herpNum) {
    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp($herpNum);
    }
}

herp($herpNum);

$herpNum = 0;

function herp() {
    global $herpNum;

    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp();
    }
}

herp();

答案 1 :(得分:3)

这是因为你没有将参数$herpnum传入函数。

<?php

$herpNum = 0;

function herp($herpNum) {
    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp($herpNum);
    }
}

herp($herpNum);

?>

那应该有用

答案 2 :(得分:2)

问题是,$herpNum每次调用herp()时都会重新定义为herp()范围内的本地变量。这将导致递归循环,直到'最大函数嵌套级别'100'达到...'抛出错误。 (当您将php ini值'display_errors'设置为'On'时,您可以看到错误)

将上面的代码更改为:

$herpNum = 0;

function herp() {
    global $herpNum;
    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp();
    }   
}

herp();

请注意,如果$herpNum仅由herp()使用,则最好将其声明为herp()内的静态变量。

function herp() {
    static $herpNum = 0;
    // ...

static关键字告诉PHP解释器它应该在第一次调用函数时初始化变量一次。这应该完全符合您的设计需求;)

答案 3 :(得分:0)

尝试:

$herpNum = 0;

function herp() {
    global $herpNum;
    if ($herpNum == 22) {
        echo "done";
    } else {
        $herpNum = $herpNum+1;
        echo $herpNum."<br/>";
        herp();
    }
}
herp();

但出于安全原因,不建议这样做。

以下是一个例子:

...
if( $admin == true ) {
  echo 'yeah! You are the admin!';
}
...

如果$admin被声明为全局且未经过正确验证,则只需输入http://mysite.com/?admin=true即可使测试通过。

顺便说一句......对于递归,最好将“environment”(一个或多个参数)作为参数注入:

herp($herpNum=0); // if nothing is given, $herpNum is set to 0
相关问题