If condition for PHP Version ignore new code

2019-05-13 16:59发布

问题:

So I've got a script that needs to run on several sites. I've got one version of the script that is optimised with some new PHP 5.3 functions, however some sites are 5.2 etc.

This code:

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
    Do the optimised 5.3 code (Although 5.2 throws syntax errors for it)
} else {
  do the slower version of code
}

However, on the 5.2 servers, it will detect the "syntax errors" in the first if condition, even though it technically should skip that content, I'm aware that PHP still scans the whole file.

How can I get 5.2 to ignore the first if completely (I know I could use "@" to ignore errors, but that feels like cheating?)

回答1:

You could include different scripts based on version, then the script with syntax that isn't valid in 5.2 would never be included for that version.

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
     include("script53.php");
} else {
     include("script52.php");
}


回答2:

Instead of the above code and calling two different functions, I suggest creating the PHP 5.3 functions you need if they don't exist. That way you only have to remember one function name instead of two.

if (!function_exists('example_func')) {
   function example_func($str,$str2) {
      return $str.$str2; 
   }
}

example_func('abc','def');