April 28, 2012

Is it possible to switch in PHP based on version?

Question by Dave M G

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 server with PHP 5.2 or earlier, then it would just be ignored. However, it turns out that when that script, and the class inside it, even just gets included, then PHP bails and stops executing.

If I can avoid it, I’d like to not have to branch of different versions of my scripts dedicated to different PHP versions. Instead, it would be ideal to be able to have code that says “If PHP version 5.3, then do this, if less, then do something different.”

I’Ve looked for some kind of “version switch” in the PHP manual, but didn’t see one.

Is a switch function like I’m describing possible?

Answer by Starx

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
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!