If condition for PHP Version ignore new code

人盡茶涼 提交于 2019-12-12 09:46:17

问题


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


来源:https://stackoverflow.com/questions/24427066/if-condition-for-php-version-ignore-new-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!