0

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.

0

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Raffael They are not really anonymous - the name is just created in runtime, but technically create_function is just a wrapper around eval + a random name generator.
@troelskn - My code is inside a class I cannot pass just the function name as it wont find it.
@Brady, if you define a method in the current class, you can refer to it with array($this, 'method_name'). Take a look at the PHP manual page about callbacks.
3

The syntax for anonymous functions in the example can only be used in PHP >= 5.3. Before PHP 5.3, anonymous functions can only be created with create_function().

1 Comment

Right. Updated answer. I always found create_function() incredibly ugly and I used it so rarely that I didn't even think about it now.
2

Anonymous functions using this function-syntax has been added 5.3. But you can define anonymous functions using http://www.php.net/manual/en/function.create-function.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.