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

查看:97
本文介绍了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天全站免登陆