如何不在 php 5.6 上执行某些 php 7 代码?

How to not execute some php 7 code on php 5.6?

最近我有必要使用 come 代码来向后兼容 PHP 5.6,我使用 if 语句来做到这一点,检查 php 版本以选择执行什么代码。 这是一个小例子:

if ( version_compare( PHP_VERSION, '7.0', '>=' ) ) {
    return strtotime($b['date']) <=> strtotime($a['date']);
}
else {
    if (strtotime($a['date']) == strtotime($b['date'])) {
        return 0;
    }
    return (strtotime($a['date']) > strtotime($b['date'])) ? -1 : 1;
}

我认为这就足够了,但事实并非如此。 PHP 仍在尝试执行 PHP 7 代码,返回飞船操作符的错误。任何人都知道为什么 php 仍在执行内部代码和 if 语句明确表示不这样做以及如何解决这个问题?谢谢

您尝试的方法不会起作用,因为解析器仍会尝试解析整个文件,并且不会识别某些 php7 语法。为防止这种情况,您需要执行以下操作:

if (version_compare(PHP_VERSION, '7.0', '>=')) {
    include('php7code.php');
}
else {
    include('php5code.php');
}

请注意,这是不可取的,会使您的代码更难测试。