尝试 Catch 不能与 PHP 中的require_once一起使用?

php
2022-08-30 13:06:11

我不能做这样的事情?

try {
    require_once( '/includes/functions.php' );      
}
catch(Exception $e) {    
    echo "Message : " . $e->getMessage();
    echo "Code : " . $e->getCode();
}

不回显任何错误,服务器返回 500。


答案 1

您可以使用 或 :include_oncefile_exists

try {
    if (! @include_once( '/includes/functions.php' )) // @ - to suppress warnings, 
    // you can also use error_reporting function for the same purpose which may be a better option
        throw new Exception ('functions.php does not exist');
    // or 
    if (!file_exists('/includes/functions.php' ))
        throw new Exception ('functions.php does not exist');
    else
        require_once('/includes/functions.php' ); 
}
catch(Exception $e) {    
    echo "Message : " . $e->getMessage();
    echo "Code : " . $e->getCode();
}

答案 2

正如你可以在这里读到的:(我的)

require() 与 include() 相同,除非发生故障时,它还会产生致命的E_COMPILE_ERROR级错误。换句话说,它将停止脚本

这是关于要求的,但这等效于require_once()。这不是一个可捕获的错误。

顺便说一句,你需要进入绝对路径,我认为这是不对的:

 require_once( '/includes/functions.php' ); 

你可能想要这样的东西

require_once( './includes/functions.php' ); 

或者,如果您从子目录或包含在不同 dirs 中的文件调用此文件,则可能需要类似

require_once( '/var/www/yourPath/includes/functions.php' ); 

推荐