PHP 8.3 新特性 - PHP CLI (php -l) 支持同时检查多个文件

作者: 温新

图书: 【PHP 8.3 新特性】

阅读: 1332

时间: 2025-03-10 23:36:37

hi,我是温新,一名 PHPer

PHP CLI Lint(php -l)在 PHP 8.3 版本中支持一次检查多个文件。可以检查传递的文件名是否存在语法错误,这有助于在执行之前快速检查 PHP 文件或代码段。

PHP 8.3

PHP 8.3 中检查多个文件

php -l 3-class-alias-1.php 3-class-alias-2.php 
    
No syntax errors detected in 3-class-alias-1.php
No syntax errors detected in 3-class-alias-2.php

从 PHP 8.3 开始,可以在同一调用中传递多个 PHP 文件和 PHP CLI lint 所有这些文件。

如果 linter 在提供的任何文件中发现任何错误,则会显示该错误,并继续执行列表的其余部分。如果任何文件未通过 lint,则存在错误。

某个文件中包含报错

php -l 3-class-alias-1.php 3-class-alias-2.php 
    
PHP Parse error:  syntax error, unexpected string content "hello" in 3-class-alias-1.php on line 10
Errors parsing 3-class-alias-1.php
No syntax errors detected in 3-class-alias-2.php

支持 Glob 模式

除了单独传递多个文件名之外,还可以使用 glob 模式来lint多个文件:

php -l php8.3/*.php

No syntax errors detected in php8.3/1-json-validate-1.php
No syntax errors detected in php8.3/1-json-validate-2.php
No syntax errors detected in php8.3/1-json-validate-3.php
No syntax errors detected in php8.3/1-json-validate-4.php
No syntax errors detected in php8.3/1-json-validate-5.php
No syntax errors detected in php8.3/1-json-validate.php
PHP Fatal error:  Type of Child::NAME must be compatible with Father::NAME of type string|int in php8.3/2-type-10.php on line 7
Errors parsing php8.3/2-type-10.php
No syntax errors detected in php8.3/2-type-1.php
PHP Fatal error:  Cannot use int as value for class constant Cat::NAME of type string in php8.3/2-type-2.php on line 4

终止代码

  • 如果有任何文件不可访问,终止代码将为 1
  • 如果任何文件 lint 失败,终止代码将是 255
  • 当两个错误条件都存在时,终止代码将为 1

< PHP 8.3

检查 1 个文件

php -l 3-class-alias-1.php

输出结果

// 没有语法错误
No syntax errors detected in 3-class-alias-1.php

假设有错误的代码

<?php
    
// test.php
    
echo 'hello'

检查代码

php -l test.php 
    
PHP Parse error:  syntax error, unexpected single-quoted string "hello" in test.php on line 3
Errors parsing test.php

检查多个文件

php -l test.php test1.php 
    
No syntax errors detected in test.php

在 PHP 8.3 之前的版本中,无论一次检查多少个文件,PHP CLI 都只对第一个文件进行 lint 检查。

请登录后再评论