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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器