php的匿名函数中如何递归自己
ringa_lee
ringa_lee 2017-04-10 13:12:16
[PHP讨论组]

php 5.2以后增加了匿名函数这个功能,但我在匿名函数递归时发现了问题

<?php

$test = NULL;
$test = function ($a) use ($test) {
    echo $a;
    $a --;

    if ($a > 0) {
        return $test($a);
    }
};

$test(10);

正如上面的代码所示,我想在$test这个匿名函数里递归调用它自己,但是我发现在调用后会出现

Fatal error: Function name must be a string in /Library/WebServer/Documents/test.php on line 9

也就是$test这个变量并不能被识别,大家有办法能在匿名函数中递归函数本身吗?

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
PHP中文网

In order for it to work, you need to pass $test as a reference

$test = function ($a) use (&$test) {
    ...
}

Reference: http://stackoverflow.com/questions/24...

tips: google helps.

PHP中文网

php5.4下通过

$test = NULL;
$test = function ($a) use (&$test) {
    echo $a;
    $a --;

    if ($a > 0) {
        return $test($a);
    }
};

$test(10);
伊谢尔伦

php递归函数例子

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号