使用匿名函数递归

daG*_*vis 1 php recursion reference anonymous-function anonymous-recursion

可能重复:
javascript:递归匿名函数?
匿名递归PHP函数

我在想......是否可以使用匿名函数进行递归?

这是一个例子:我需要得到六个字符长的字符串,它可能只包含数字和空格.唯一的规则是它不能以空格开头或结尾.我们检查一下,如果发生这种情况 - 只需在相同的匿名函数上调用递归.怎么样!?

function() {

    $chars   = range(0, 9);
    $chars[] = ' ';
    length   = 6;
    $count   = count($chars);

    $string = '';
    for ($i = 0; $i < $length; ++$i) {

        $string .= $chars[mt_rand(0, $count - 1)];

    }

    $string = trim($string);

    if (strlen($string) !== $length) { // There were spaces in front or end of the string. Shit!

        // Do recursion.

    }

    return $string;

}
Run Code Online (Sandbox Code Playgroud)

小智 14

是的,但我不推荐它,因为它有点棘手;)

第一种可能性

<?php
$some_var1="1";
$some_var2="2";
function($param1, $param2) use ($some_var1, $some_var2)
{
    call_user_func(__FUNCTION__, $other_param1, $other_param2);
}
?>
Run Code Online (Sandbox Code Playgroud)

另一个:

<?php 
$recursive = function () use (&$recursive){ 
    // The function is now available as $recursive 
} 
?> 
Run Code Online (Sandbox Code Playgroud)

http://php.net/获取的示例

  • +1第二个真的很优雅!我一直认为你需要使用那个看起来很疯狂的Y-Combinator来做Lambda-Recursion;) (2认同)