Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Conditional Using PHP Version [duplicate]

Tags:

php

So my goal right now is to detect the user's PHP version (not an issue), and then run an if else based on it

So if I write something like this:

if (PHP => 5.3){
// call a function anonymously
}
else {
// if user does not have 5.3, this else block disables the feature. 
}

the issue I'm having is I want to use PHP's anonymous functions if the user has 5.3 or greater (since they were introduced in PHP 5.3) and an alternative if they have an older version. The problem is, of course, that if a user has PHP 5.2.17 for instance, that while that if statement will never evaluate as true, a fatal error will be thrown for syntax since the anonymous function call looks like a syntax error to PHP 5.2.17

Is there a way to do something like the above? The only work around I've found is to put the stuff in the if in a new file, and the stuff in the else in another, and do something like this:

$version = '5.2';//user's current version cut to the nearest x.y, ex 5.3, 5.4, 5.5
// Remove the period here, so we have 5.2
require 'function'.$version.'.php';

Now this will work fine, since function53.php will never be loaded for a 5.2 user. However it's not ideal to have to use separate files.

After reading the comment's to Ales's quesiton, something like this:

if ($version > '5.3'){
// require one file
}
else{
// require another
}

Will not work. PHP's compiler will run both files on compilation checking for syntax errors before execution and throw the error I'm trying to avoid. The only way for the file method to work is to dynamically pick a file based on version number. This requires a seperate file for every x.y release from PHP 4 and 5. Not ideal.

On Alex's answer, it works fine. We're talking one line of eval (required to hide the anonymous function call), versus the proposed tons of files.

like image 723
Chris Avatar asked Mar 24 '23 10:03

Chris


1 Answers

$version = explode('.', PHP_VERSION);
if ($version[0] > 5 || ($version[0] == 5 && $version[1] >= 3)) {
    //include with anonymous functions
    include 'file1.php';
} else {
    //include alternatives
    include 'file2.php';
}

Since you can't add php5-code directly in the code and you don't want to include a file there is a way to use create_function() where you put your code as a string, that is not pretty either, but could do the job for you.

like image 192
luk2302 Avatar answered Apr 01 '23 15:04

luk2302