PHP-使用新功能时,如何避免在旧服务器上解析错误 [英] PHP - How to avoid Parse errors on older servers when using new functions

查看:96
本文介绍了PHP-使用新功能时,如何避免在旧服务器上解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用匿名函数(但也请参见下面的注释)时:

When I use an anonymous function ( but see also note below ) like :

$f = function() use ($out) {
                echo $out;
            };

它在PHP早于5.3.0的服务器上产生解析错误. 我的软件需要与未知服务器兼容,但是与此同时,我也想使用新功能,所以我想我会添加某种版本检查功能,

It produces an parse error on servers where PHP is older than 5.3.0. My software needs to be compatible with unknown servers , but in the same time , I want also to use new functions, so I thought I will add some kind of a version check,

if (o99_php_good() != true){
            $f = function() use ($out) {
                echo $out;
            };
        }

o99_php_good()只是

function o99_php_good(){
    // $ver= ( strnatcmp( phpversion(),'5.3.0' ) >= 0 )? true:false;
    $ver= ( version_compare(PHP_VERSION, '5.3.0') >= 0 )? true:false;
return $ver;
}

但是仍然会产生错误.

是否有办法以某种方式隔离"部分代码?

Is there a way to somehow "isolate" that part of the code ?

我考虑过基于版本检查进行条件下的include(),这也许行得通,但是每次我需要使用函数时都创建一个单独的文件是荒谬的.

I thought of doing a conditional include() based on a version check , which would probably work, but it will be absurd to make a separate file every time I need to use a function...

对此有任何创意(或琐碎的)解决方案吗?

Any creative ( or trivial ) solution for that ?

注意:此处的示例仅是Lambda函数,但是该问题可能发生在其他所有新功能中,并且/或者某些服务器可能不支持此功能.

Note : the example here is just a Lambda function, but the problem can occur in every other function which is a new feature and/or might not be supported on some servers ..

在评论后编辑我.

添加最低要求"列表总是很好的,但不能解决问题.

Adding a "minimum requirements" list is always good, but it does not resolve the problem.

如果不希望失去用户(不是所有客户都满意,或者每次我将要更新新功能时都不能升级服务器),这只会迫使我将我的软件分叉"成2个(或可能更多)难以管理的软件版本.

If one does not want to loose users (not all customers are happy or can upgrade their servers every time I will update a new function ) it will just force me to "fork" my software into 2 (or possibly more ) unmanageable versions..

推荐答案

我遇到了完全相同的问题,并使用eval函数解决了这个问题:

I had exactly the same problem and solved it using eval function :

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
eval('
function osort(&$array, $prop)
{
    usort($array, function($a, $b) use ($prop) {
        return $a->$prop > $b->$prop ? 1 : -1;
    }); 
}
');
} else {
    // something else...
}

这篇关于PHP-使用新功能时,如何避免在旧服务器上解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆