2015-06-19 58 views
1

我想請問,我可以要求/包括有語法錯誤,如果我不能,則需要/包括返回一個值,讓我知道所需的文件/包含的文件有語法錯誤,不能被要求/包括在內?包括需要一個語法錯誤文件

file.php有語法錯誤

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

回答

3

如果你真的想要這種類型的功能。

你可以嘗試使用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(); 
} 
-1

你可以使用的東西IKE在此:

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

@用來隱藏錯誤消息

+0

這將隱藏包括本身的錯誤。操作詢問關於語法錯誤。 – Federkun

+0

@Leggendario如果是這樣的問題,那麼問題就沒有意義了。在包含之前,PHP不檢查這樣的錯誤。它首先包括文件,然後讀取它(反過來是不可能的,對不對?) – FeedTheWeb

+0

如果包含的文件有語法錯誤,停止執行,即使有錯誤抑制。沒有超過包括將工作。 – castis

0

在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";