Search code examples
phpanonymous-functionpreg-replace-callback

How can I code for multiple versions of PHP in the same file without error?


I'm trying to support two versions of some PHP code in one file using version_compare, but I still get an error.

Code:

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
    $alias = preg_replace_callback('/&#x([0-9a-f]{1,7});/i', function($matches) { return chr(hexdec($matches[1])); }, $alias);
    $alias = preg_replace_callback('/&#([0-9]{1,7});/', function($matches) { return chr($matches[1]); }, $alias);
} else {
    $alias = preg_replace('/&#x([0-9a-f]{1,7});/ei', 'chr(hexdec("\\1"))', $alias);
    $alias = preg_replace('/&#([0-9]{1,7});/e', 'chr("\\1")', $alias);
}

But I get:

PHP Parse error: syntax error, unexpected T_FUNCTION

On the preg_replace_callback() calls, probably because of the anonymous functions.


Solution

  • It is not possible to use version checking to decide to use a language feature that will cause a parse error in a previous version. The parser looks at the whole file, regardless of branching.

    If the lint check fails for that version, it won't work, regardless of branching:

    > php -l file.php
    > PHP Parse error: syntax error, unexpected T_FUNCTION