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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)