【问题标题】:PHP anonymous function causes syntax error on some installationsPHP 匿名函数在某些安装中导致语法错误
【发布时间】:2011-09-18 17:09:31
【问题描述】:

我有以下代码:

    $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']);

这适用于我的 PHP 5.3.5 安装,但是当我在 PHP 5.2.15 安装上运行此代码时,我得到:

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

第 220 行是上述代码的第一行。

所以我的问题是,我的代码中是否有错误的内容会导致此错误?如果不是,是因为 PHP 5.2.15 中的错误或不支持的功能?如果是,那么我该如何编写上述代码以免产生错误?

以上代码在一个类的函数中。

【问题讨论】:

    标签: syntax-error php anonymous-function


    【解决方案1】:

    匿名函数是 5.3 中添加的功能

    对于早期版本,创建一个命名函数并按名称引用它。例如:

    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']);
    

    或在类内:

    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;
      }
    }
    

    我强烈建议不要依赖create_function

    【讨论】:

    • @Raffael 他们并不是真正匿名的——名称只是在运行时创建的,但从技术上讲,create_function 只是 eval 的包装器 + 一个随机名称生成器。
    • @troelskn - 我的代码在一个类中,我不能只传递函数名,因为它找不到它。
    • @Brady,如果你在当前类中定义了一个方法,你可以用array($this, 'method_name')引用它。查看有关callbacks 的PHP 手册页。
    【解决方案2】:

    示例中匿名函数的语法只能在 PHP >= 5.3 中使用。 PHP 5.3 之前,匿名函数只能用create_function() 创建。

    【讨论】:

    • 对。更新了答案。我总是觉得create_function() 非常丑陋,而且我很少使用它,以至于我现在都没有考虑过。
    【解决方案3】:

    5.3 中添加了使用此函数语法的匿名函数。但是你可以使用http://www.php.net/manual/en/function.create-function.php定义匿名函数

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 2017-10-12
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2010-12-10
      • 2017-01-01
      • 2019-12-11
      相关资源
      最近更新 更多