PHP code version dependency

2019-05-26 05:02发布

In each and every version of php, some new features are added and some features are stopped.

Example:

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

will need php 5.4.0 and above, as hex2bin was introduced in php 5.4.0.
It is tedious to check version dependency manually in php.net for each and every built-in functions used in php code. Is there any automated/semi-automated way to identify the minimum version (and maximum version if applicable) of php installation would be needed to execute any given php code?

5条回答
Melony?
2楼-- · 2019-05-26 05:31

You can create a manual checking ,then using 'patch'.To define what is missing.

Using phpversion();

 if (strnatcmp(phpversion(),'5.2.10') >= 0) 
 { 
       //loading patch

 } 
 else 
 { 
     //loading patch
      function abc(){
        //
      }
 } 
查看更多
forever°为你锁心
3楼-- · 2019-05-26 05:33

Check out the PHPCompatibility project : https://github.com/wimg/PHPCompatibility This tests your code for compatibility with 5.2, 5.3, 5.4 and 5.5(alpha2 at the time of writing)

查看更多
Bombasti
4楼-- · 2019-05-26 05:36

Don't know if there is a way to check in php wich version is needed, but you could use "function_exists" to see if your version of php has that function.

http://php.net/manual/en/function.function-exists.php

<?php
if (function_exists('hex2bin')) {
    echo "hex2bin function is available.<br />\n";
} else {
    echo "hex2bin function is not available.<br />\n";
}
?>
查看更多
啃猪蹄的小仙女
5楼-- · 2019-05-26 05:41

Good practice could be to have fallbacks. Just like mentioned in this function, there are alternatives.

if ( ! function_exists('hex2bin')) {
    function hex2bin($hexstr)
    {
        $n = strlen($hexstr);
        $sbin="";  
        $i=0;
        while($i<$n)
        {      
            $a =substr($hexstr,$i,2);          
            $c = pack("H*",$a);
            if ($i==0){$sbin=$c;}
            else {$sbin.=$c;}
            $i+=2;
        }
        return $sbin;
    }
}

Code is based on Johnson's reply.

Setting essential function which does that same as new ones in case they don't exist lets you go about your business without having to fear incompability. Just hide these where you don't have any reason to edit them and they won't bother you either.

查看更多
在下西门庆
6楼-- · 2019-05-26 05:50

It's up to the programmer to state the dependencies of his or her library / project.

Many projects now use Composer as a dependency manager, but for legacy code you can't do much but running it and swearing against errors.

查看更多
登录 后发表回答