Is it possible to switch in PHP based on version?

前端 未结 4 1166
一生所求
一生所求 2021-01-25 17:48

I have a function in one of my PHP scripts that relies on version 5.3 to run.

I thought that if it was in a function that didn\'t happen to get called when run on a serv

相关标签:
4条回答
  • 2021-01-25 18:11

    There are numerous ways to solve this. I prefer detecting the version and executing function.

    1. There is a function called phpversion() or constant PHP_VERSION that gives you the current php version

      Use them like

      if(phpversion() == '5.3') {
        //specific php functions
      }
      
    2. To check if the current version is newer or equal to lets say '5.3.2'. simply use:

      if (strnatcmp(phpversion(),'5.3.2') >= 0) {
          # equal or newer
      }
      else {
         # not 
      }
      
    3. Or, use version_compare to know

      if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
          echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
      }
      

    Or ever more user friendly version is to use function_exists()

    if (!function_exists('function_name')) {
        // the PHP version is not sufficient
    }
    
    0 讨论(0)
  • 2021-01-25 18:16

    Have a separate code file with your PHP 5.3+ code, and only include() it if you detect 5.3 or greater.

    0 讨论(0)
  • 2021-01-25 18:20

    You might look at implementing PHP 5.3+ functions if they don't exist.

    if (!function_exists('array_replace')) {
        function array_replace(....) {
            // logic here
        }
    }
    

    If you have to detect the version, you can use PHP_VERSION.

    0 讨论(0)
  • 2021-01-25 18:35

    Have a look at the PHP predefined constants. They include several constants that define the running version. You could use that to decide which version of a script to load.

    0 讨论(0)
提交回复
热议问题