dongqun9403 2011-06-20 13:37
浏览 48
已采纳

PHP匿名函数在某些安装上导致语法错误

I have the following code:

    $file_check_method_func = function($n) {
        $n = absint($n);
        if(1 !== $n) { $n = 0; }
        return $n;
    };
    $valid['file_check_method'] = array_map($file_check_method_func, $input['file_check_method']);

This works on my PHP 5.3.5 installation but when I run this code on a PHP 5.2.15 installation I get:

Parse error: syntax error, unexpected T_FUNCTION in /home/xxxx/public_html/xxxx/xxxxxxx/wp-content/plugins/wordpress-file-monitor-plus/classes/wpfmp.settings.class.php on line 220

Line 220 being the first line of the above code.

So my question(s), is there something wrongly written in my code that would give this error? If not is it because of a bug or not supported feature in PHP 5.2.15? If yes then how can I write the above code so not to generate the error?

The above code is in a function in a class.

  • 写回答

3条回答 默认 最新

  • ds42774 2011-06-20 13:37
    关注

    Anonymous functions is a feature added in 5.3

    For earlier versions, create a named function and refer it by name. Eg.:

    function file_check_method_func($n) {
        $n = absint($n);
        if(1 !== $n) { $n = 0; }
        return $n;
    }
    $valid['file_check_method'] = array_map('file_check_method_func', $input['file_check_method']);
    

    or inside a class:

    class Foo {
      protected function file_check_method_func($n) {
        $n = absint($n);
        if(1 !== $n) { $n = 0; }
        return $n;
      }
      function validate($input) {
        $valid = array();
        $valid['file_check_method'] = array_map(array($this, 'file_check_method_func'), $input['file_check_method']);
        return $valid;
      }
    }
    

    I would strongly suggest not to rely on create_function.

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案