Articles
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


When an author readies his application to be published, he will certainly has to check if the hosting PHP version will be consistent with the one he needs. To make this analyze easier, there is the function version_compare(). It will make a first compatibility test.

Example n°1 :

<?php
 
 
    /**
     * PHP version needed
     */
    define('MY_PHP_VERSION', '5.2.1');
 
 
    switch (version_compare(MY_PHP_VERSION, <a href="http://www.php.net/phpversion">phpversion()</a>)) {
        case '0':
            echo 'Your PHP version is good for this application.';
        break;
        case '-1':
            echo 'This PHP version is newer than requested. Proceed with caution.';
        break;
        case '+1':
            echo 'Your PHP version must be upgraded before using this application. ';
        break;
    }
 
 
?>

phpversion(), without argument, returns the actual PHP constante PHP_VERSION. On certain specific servers, this value is not the best choice to make a comparison.

Example n°2 :

<?php
 
 
    /**
     * PHP version needed
     */
    define('MY_PHP_VERSION', '5.2.1');
 
 
    /**
     * PHP_VERSION = 5.1.6-pl6-gentoo
     * We must make it simpler : 5.1.6
     */
    define('PHP_VERSION_SIMPLE', substr(PHP_VERSION, 0, 5));
 
 
    /**
     * Now, we may compare them
     */
    switch (version_compare(MY_PHP_VERSION, PHP_VERSION_SIMPLE)) {
        case '0':
            echo 'Your PHP version is good for this application.';
        break;
        case '-1':
            echo 'This PHP version is newer than requested. Proceed with caution.';
        break;
        case '+1':
            echo 'Your PHP version must be upgraded before using this application. ';
        break;
    }
 
 
?>

version_compare() permet d'émuler un opérateur type <=>

Example n°3 :
<?php
 
 
// emulation d'un op&eacute;rateur <=>
$a = 1;
$b = 2;
 
 
var_dump(version_compare($a, $b));
var_dump(version_compare($b, $a));
 
 
/**
  * int(-1)
  * int(1)
  */
?>


Attention: this function is available since PHP 4.0.7. If your want to use this on an even older PHP installation, you'll have to design your own comparison function.

Keep in mind

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter