Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 353
orbitory Avatar asked Feb 28 '15 22:02

orbitory


People also ask

How can I have multiple versions of PHP?

Add a PHP Repository So you'll need to add the PHP repository in your system to install the multiple PHP versions. Once the repository is up-to-date, you can proceed to install multiple PHP versions.

Can I run several versions of PHP at the same time?

Yes we can run several versions of php. To do that we must have to check the INSTALL file, if it is included in PHP source distribution.

What is the best function to use to include a PHP file that contains multiple functions?

In PHP, there are two functions that are used to put the contents of a file containing PHP source code into another PHP file. These function are Include() and Require().


1 Answers

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);
like image 156
jerdiggity Avatar answered Oct 29 '22 03:10

jerdiggity