【问题标题】:Include, Require a syntax error file包含,需要一个语法错误文件
【发布时间】:2015-09-05 16:41:00
【问题描述】:

我想问我是否可以要求/包含一个有语法错误的文件,如果我不能,要求/包含返回一个值,以便我知道所需/包含的文件有语法错误并且不能被要求/包含?

file.php 有语法错误

include('file.php')
if (not file.php included because of syntax)
   this
else
   that

【问题讨论】:

    标签: php include syntax-error require


    【解决方案1】:

    在 PHP 7 中,可以捕获解析错误,这可能是最强大、最优雅的内置解决方案:

    <?php
    
    function safe_require_once(string $fname) {
        try {
            require_once($fname);
        } catch( Throwable $e ) {
            //will throw a warning, continuing execution...
            trigger_error("safe_require_once() error '$e'", E_USER_WARNING);
        }
    }
    
    safe_require_once("./test1.php"); //file with parse or runtime errors
    echo "COMPLETED SUCCESSFULLY THO";
    

    【讨论】:

      【解决方案2】:

      如果你真的想要这种类型的功能。

      您可以尝试使用nikics php parser 看看是否可以成功解析文件。

      $code = file_get_contents('yourFile.php');
      
      $parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative);
      
      try {
          $stmts = $parser->parse($code);
          // $stmts is an array of statement nodes
          // file can be successfully included!
      } catch (PhpParser\Error $e) {
          // cannot parse file!
          echo 'Parse Error: ', $e->getMessage();
      }
      

      【讨论】:

        【解决方案3】:

        你可以使用这样的东西:

        if((@include $filename) === false)
        {
            // handle error
        } else { //....}
        

        @ 用于隐藏错误信息

        【讨论】:

        • 这将隐藏包含本身的错误。操作询问语法错误。
        • @Leggendario 如果这是问题,那么这个问题没有意义。 PHP 在包含之前不会检查此类错误。它首先包含文件,然后读取它(反过来是不可能的,对吧?)
        • 如果包含的文件有语法错误,即使使用错误抑制器,也会停止执行。包含在内的任何内容都不起作用。
        • @Ixer 没有人说这个问题有道理啊
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-31
        • 2012-07-03
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        • 2012-04-22
        相关资源
        最近更新 更多