PHP - How to avoid Parse errors on older servers when using new functions

谁说我不能喝 提交于 2019-12-05 20:43:40

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...
}

The only thing I can think of is to make a build script which people will have to run to make it compatible with lower versions.

So in case of anonymous methods, the script will loop through all the PHP files, looking for anonymous methods:

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

and replace them with create_function for < 5.3:

$f = create_function('$a', '
    global $out;
    echo $a . $out;
');

Anonymous functions came with PHP 5.3.0.
My first thing to do would be to replace with one of the following:

$my_print_r = "my_print_r";
$my_print_r();

or

$my_print_r = create_function('$a','print_r($a);');


UPDATE:

i would go with the first method... It would give me enough control for creating my own function versions and in much easier procedure than create_function, regardless of PHP version. I never had any problems with that approach. In fact i once built a whole multidimensional array of functions, that was easily manageable and able to add/remove functions, think of that.. That system was also used by other users, they were able to add their functions too in a way.

use include

if (o99_php_good() != true){
include 'new_func.php';
        }

new_func.php:

        $f = function() use ($out) {
            echo $out;
        };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!