Anonymous function returns: syntax error, Unexpected T_FUNCTION

Asked

Viewed 3,027 times

2

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?

1 answer

5


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

Source:

http://php.net/manual/en/functions.anonymous.php

Check PHP version:

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

<?php
phpinfo();

It is also possible to do this by command line, type in terminal or SSH:

php -i or php -v

If you need to maintain compatibility with older versions 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');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.