使用PHP版本运行条件

时间:2013-06-24 12:31:47

标签: php

所以我现在的目标是检测用户的PHP版本(不是问题),然后根据它运行if else

所以,如果我写这样的话:

if (PHP => 5.3){
// call a function anonymously
}
else {
// if user does not have 5.3, this else block disables the feature. 
}

我遇到的问题是,如果用户拥有5.3或更高版本(因为它们是在PHP 5.3中引入的话),我想使用PHP的匿名函数,如果他们有旧版本,则可以使用它。问题是,当然,如果用户具有PHP 5.2.17,那么if语句永远不会被评估为true,因为匿名函数调用看起来像PHP的语法错误,因此会抛出致命错误。 5.2.17

有没有办法做上面这样的事情?我发现的唯一工作就是把if放在一个新文件中,把else放在另一个文件中,然后做这样的事情:

$version = '5.2';//user's current version cut to the nearest x.y, ex 5.3, 5.4, 5.5
// Remove the period here, so we have 5.2
require 'function'.$version.'.php';

现在这样可以正常工作,因为函数53.php永远不会为5.2用户加载。但是,必须使用单独的文件并不理想。

在阅读了Ales的问题评论后,就像这样:

if ($version > '5.3'){
// require one file
}
else{
// require another
}

不行。 PHP的编译器将在执行前对编译检查语法错误运行这两个文件并抛出我试图避免的错误。文件方法工作的唯一方法是根据版本号动态选择文件。对于PHP 4和5中的每个x.y版本,这都需要一个单独的文件。不太理想。

在亚历克斯的回答中,它运作正常。我们正在讨论一行eval(需要隐藏匿名函数调用),而不是提议的大量文件。

3 个答案:

答案 0 :(得分:3)

$version = explode('.', PHP_VERSION);
if ($version[0] > 5 || ($version[0] == 5 && $version[1] >= 3)) {
    //include with anonymous functions
    include 'file1.php';
} else {
    //include alternatives
    include 'file2.php';
}

很抱歉,我在下面输入的代码是错误的-.-

由于你不能直接在代码中添加php5代码而你不想包含文件,所以有一种方法可以使用create_function()将代码放在字符串中,这不是很好要么,但能为你做好工作。

答案 1 :(得分:2)

你可以只评估代码,它可以动态编译。

$res = -1
if (PHP => 5.3){
    eval('$res = [some advanced PHP 5.3 fast code]');
}
else {
    $res = [some basic PHP 4 code still supported by 5.3, just deprecated];
    eval('$res = [some real rudimentary PHP 4 code no longer supported at all in 5.3]');
}
$res = $res + 1;
echo $res;

if (PHP => 5.3){
    eval('$res = [some more advanced PHP 5.3 fast code]');
}
else {
    $res = [some more basic PHP 4 code still supported by 5.3, just deprecated];
    eval('$res = [some more real rudimentary PHP 4 code no longer supported at all in 5.3]');
}

了解以这种方式包含50个不同文件会有多痛苦,但是eval会让它变得简单吗?他的文件中存在大的重叠区域,因此他不想仅仅制作两个单独的文件,因此他想要一种方法在他的文件中间运行两个独立的代码段。

答案 2 :(得分:2)

对于每个功能,请定义一个功能。如果您需要针对这些版本的特定版本差异,请为每个版本创建一个文件。 E.g:

features_5.3.php

function foo() { ... }

function bar() { ... }

features_5.2.php

function foo() { ... }

function bar() { ... }

然后检查您正在运行的版本并包含相应的文件:

if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
    require_once 'features_5.3.php';
} else {
    require_once 'features_5.2.php';
}

然后在需要时使用您的功能:

foo();

对于不支持这些功能的PHP版本,只需将foo()作为无操作;或者在需要调用时检查功能是否支持:

if (function_exists('foo'))

或设置常量:

if (FEATURE_FOO_AVAILABLE) {
    foo();
}