静态变量打印正确的值,但返回 null


Static variable prints the correct value but returns null

我有一个奇怪的情况。看看这个。我不知道为什么 $counter 变量打印 6,但不返回 6。

function myTest($bin) {
    static $counter = 0;
    if ($bin == 0) {
        // echo $counter; // prints 6
        return $counter;
    }
    $rem = $bin % 2;
    if($rem == 0) {
        $counter++;
        $bin = $bin / 2;
        myTest($bin);
    }
    else {
        $counter++;
        $bin = $bin - 1;
        myTest($bin);
   }
}
$test = mytest(11);
var_dump($test); // Returns NULL

编写递归函数时,必须"返回"递归调用,如

return myTest($bin);

如果没有递归调用的返回,对函数的原始调用不会返回任何内容。因此,$test为 null(未返回任何内容)。