尝试Catch无法在PHP中使用require_once?

use*_*291 30 php

我做不到这样的事情?

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

没有错误被回应,服务器返回500.

a1e*_*x07 53

您可以使用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();
}
Run Code Online (Sandbox Code Playgroud)

  • 太好了!但仍然是一行:if(!file_exsists('/ includes/functions.php')) (2认同)

Nan*_*nne 10

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

require()与include()相同,除非失败,它还会产生致命的E_COMPILE_ERROR级别错误.换句话说,它将停止脚本

这与require有关,但这相当于require_once().这不是一个可捕获的错误.

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

 require_once( '/includes/functions.php' ); 
Run Code Online (Sandbox Code Playgroud)

你可能想要这样的东西

require_once( './includes/functions.php' ); 
Run Code Online (Sandbox Code Playgroud)

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

require_once( '/var/www/yourPath/includes/functions.php' ); 
Run Code Online (Sandbox Code Playgroud)


Jus*_*tin 5

这应该工作,但它有点像黑客.

if(!@include_once("path/to/script.php")) {
    //Logic here
}
Run Code Online (Sandbox Code Playgroud)