Bra*_*ady 0 php syntax-error anonymous-function
我有以下代码:
$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']);
Run Code Online (Sandbox Code Playgroud)
这适用于我的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
Run Code Online (Sandbox Code Playgroud)
第220行是上述代码的第一行.
所以我的问题是,我的代码中是否写错了会出现此错误?如果不是因为PHP 5.2.15中的错误或不支持的功能?如果是,那么我如何编写上面的代码以免产生错误?
上面的代码是一个类中的函数.
匿名函数是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']);
Run Code Online (Sandbox Code Playgroud)
或在课堂内:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我强烈建议不要 依赖create_function.