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

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


One option would be to put the code in separate files, like so:

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {    include('file-5.3.0.php');} else {    include('file-5.x.php');}

Then inside file-5.3.0.php, add the corresponding code:

$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);

... and inside file-5.x.php add the remaining code:

$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);


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


Parsing PHP files happens before any code is run. The if-approach will never work across the same code unit - ie. PHP file. (And no, I will not be one to suggest "eval".)

However, if there was a different included file (one for each version), then the if could choose which file to include - but each of the files must still be syntactically valid in the PHP version/context in which it is parsed.

This is actually a "sane" approach to use if using Dependency Injection or some variation thereof - if it is really important to maintain different component implementations. This is because the IoC container / setup will determine which file(s)/implementation(s) to include and the service consumers will be agnostic to the change.