Anonymous function returns: syntax error, unexpected T_FUNCTION

3

When trying to use this function:

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');

PHP returns this error:

  

Parse error: syntax error, unexpected T_FUNCTION

How to solve?

    
asked by anonymous 17.02.2015 / 14:15

1 answer

6

If you are getting this error it is because your PHP is an "old" version. Anonymous functions are available from PHP 5.3.0.

Source:

link

Check PHP version:

To check which version of PHP is running on your machine or server, create a file and add it to the content:

<?php
phpinfo();

You can also do this by command line, type in terminal or SSH:

php -i or php -v

If you need to maintain compatibility with versions older than 5.3 you can simply do this:

<?php
function MeuReplace($match) {
    return strtoupper($match[1]);
}

echo preg_replace_callback('~-([a-z])~', 'MeuReplace', 'hello-world');
    
17.02.2015 / 14:15