PHP 匿名函数在某些安装中导致语法错误 [英] PHP anonymous function causes syntax error on some installations

查看:17
本文介绍了PHP 匿名函数在某些安装中导致语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    $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 安装上运行此代码时,我得到:

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

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

Line 220 being the first line of the above code.

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

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.

推荐答案

匿名函数是 5.3 新增的功能

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

或在类内:

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.

这篇关于PHP 匿名函数在某些安装中导致语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆