-1

我希望我团队的每个成员(可靠地)报告他们正在检查其语法的 PHP 版本。我的团队成员拥有各种操作系统、IDE 和文本编辑器,以及各种 PHP 语法检查器插件,以及php具有不同版本的多个可执行文件。例如,要求他们运行php -v,可能会向他们的编辑器用于语法检查的版本报告不同的版本。

我开始研究版本之间语言语法的变化,我的想法是我可以编写一个 PHP 文件,该文件将在不同版本中触发不同的语法错误。例如,在 PHP 8.0 中,match现在是保留关键字。此代码在 7.4 中有效,并unexpected token ";"在 8.0 中触发:

<?php
$a = match;

是否可以通过在文本编辑器中检查其语法来推断可执行文件的版本号的方式编写 PHP 文件php

4

1 回答 1

0

我同意@CatchAsCatchCan 和@El_Vanja 在评论中提出的观点。所有项目都应该有一个约定的 PHP 版本,并且所有贡献者都应该知道如何为每个项目设置他们的 PHP 版本。此外,所有更改都应由某个中央构建/CI 系统自动进行语法检查。如果缺少其中任何一个,那么实现这些都是时间和金钱的投资。

如果在达到这些目标之前,您需要一个额外的工具来帮助您排除编辑器的 PHP 语法检查器的故障,我制作了这个脚本:

<?php

// Check the syntax of this file with whatever tool you normally use
// (for example: your IDE / Sublime Text with a plugin / php -v <filename> )
// Compare the syntax error it reports with the comments below to
// determine which PHP version you have.


// PHP 8.0 will output:
// PHP Parse error:  syntax error, unexpected token ";", expecting "(" in php_syntax_version.php on line 10
$a = match;

// PHP 7.4 will output:
// PHP Parse error:  syntax error, unexpected 'fn' (T_FN), expecting identifier (T_STRING) in php_syntax_version.php on line 14
class fn{}

// PHP 7.3 will output:
// Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in file on line 19
$str = <<<FOO
abcdefg
   FOO
FOO;

// PHP 7.2 will output:
// PHP Fatal error:  Cannot use 'object' as class name as it is reserved in php_syntax_version.php on line 25
class object{}

// PHP 7.1 will output:
// PHP Fatal error:  Cannot use 'iterable' as class name as it is reserved in php_syntax_version.php on line 29
class iterable{}

// PHP 7.0 AND 5.6 will BOTH output (SEE BELOW):
// No syntax errors detected in php_syntax_version.php


// -------------------------------------------------------
// To tell between 5.6 and 7.0, uncomment these two lines:
// class C {}
// $c =& new C;

// PHP 7.0 will output:
// PHP Parse error:  syntax error, unexpected 'new' (T_NEW) in php_syntax_version.php on line 39 !! Do not compare on the line number alone, as this can be misleading. !!

// PHP 5.6 will output:
// PHP Deprecated:  Assigning the return value of new by reference is deprecated in php_syntax_version.php on line 39 !! Do not compare on the line number alone, as this can be misleading. !!

于 2020-12-17T00:11:50.820 回答