-->

是否有可能从PHP PHP检查文件的语法?(Is it possible to check PHP

2019-07-31 03:05发布

我动态加载PHP类文件与自动加载。 而这些文件可能丢失或由于某种原因损坏。

自动加载成功会报告丢失的文件,以便应用程序逻辑可以搞定。 在错误日志:但是,如果这些文件被损坏,那么整个处理空白屏幕为用户和“语法错误PHP解析错误”暂停。

是否有可能从PHP代码检查PHP文件的语法?

我在这里看: http://us.php.net/manual/en/function.php-check-syntax.php -它过时。

exec("php -l $file");

似乎是一个错误的方式( http://bugs.php.net/bug.php?id=46339 )

思考?

Answer 1:

你真的不应该尝试检查在执行时不正确的PHP文件:它会杀了你的应用程序的响应时间!

A“更好的方式”是使用PHP -l命令行大功告成修改PHP脚本时; 或者它包括在你的构建过程中,如果你使用一个; 或插入它作为一个SVN如果你使用SVN pre-commit钩子,可以定义SVN挂钩 。

在我看来,几乎任何给定的解决方案是不是检查自己在执行时更好!


考虑到像你想避免将可能不会经常发生的那些错误,它可能是更好的...只是让他们发生。
唯一的一点是:启动日志,并监视他们来说,能够快速检测时泰雷是一个问题:-)


当然,这并不妨碍你处理丢失的文件的情况; 但是这是一个不同的问题...



Answer 2:

另一种方法可以让一个PHP文件在你所谓的checkSyntax.php根目录

<?php
for($i=1; $i < count($argv); $i++){
        $temp = "php -l " . $argv[$i];
        $output = exec($temp);
        echo "\n$output";
}
?>

现在,打开你的.bashrc文件,以建立一个快捷方式运行此文件。 下面添加行运行checkSyntax.php

alias checkSyntaxErrors='php /root/checkSyntax.php'

现在后藤源目录中运行svn ST。

它可以显示文件列表,现在可以轻松地运行命令。

checkSyntaxErrors file1.php file2.php .......

这将检查所有文件传递作为参数。

请享用 :)



Answer 3:

In short: i can't see a way to do this, but have an idea which might be sufficient.

There are log monitoring programs or can filter the logs via standard tools for files with parse errors. If a file appears, you put the villain filename into a black list and your autoloader checks before load against this list.

With this method, at first time you'll serve a blank screen (assumig error reporting to the output are turned on on production servers) but the second will have a page without the faulty component.

In the autoloader you should have a list or naming scheme to always try to loading mandatory classes (other ways your application might be in an inconsistent state)



Answer 4:

你也可以做一些单元测试,在这里装载你动态地执行PHP和断言EXEC(“PHP -l $文件名”)是有效的。 如果你这样做,你可以在你的测试一次验证,具有相应的变量产生的,并有合理的置信水平你的PHP是好的。



文章来源: Is it possible to check PHP file syntax from PHP?