dongzhuange2625 2011-05-10 15:05
浏览 51
已采纳

“usort”中的排序函数在PHP中被“唤醒”了吗? 致命错误:无法重新声明功能?

Recently stumbled upon this neat little bug or 'feature' in PHP:

function myCmpFunc($a,$b) {
    function inner($p) {
         // do something
    }
    $inner_a = inner($a);
    $inner_b = inner($b);
    if ($inner_a == $inner_b) return 0;
    return ($inner_a > $inner_b ? -1 : 1);
}

Results in a fatal error "cannot redeclare function inner in ...", when called like this

usort($myArray, 'myCmpFunc');

It works flawlessly when function inner is declared outside of myCmpFunc and/or $myArray has not more than 2 elements ;)

-- edit --

somehow Related: PHP Fatal error: Cannot redeclare function

So here is my question, then: Is it possible to declare functions in local scope?

-- edit 2 --

Maybe, this works well in PHP 5.3 just read it has closures, yeehaa!

  • 写回答

4条回答 默认 最新

  • dou4121 2011-05-10 15:15
    关注

    function inner($p) is defined each time that function myCmpFunc($a,$b) is executed. Furthermore, the inner function is visible outside function myCmpFunc($a,$b) after that (which pretty much takes the sense out of allowing nested function definitions). That's why you get a duplicate definition error when you call the outer function a second time.

    To work around this, check whether function_exists in the body of function myCmpFunc($a,$b).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题