Try Catch cannot work with require_once in PHP?

前端 未结 3 888
傲寒
傲寒 2020-12-01 07:54

I can\'t do something like this ?

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


        
相关标签:
3条回答
  • 2020-12-01 08:06

    You can do it with include_once or file_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();
    }
    
    0 讨论(0)
  • 2020-12-01 08:08

    As you can read here : (emph mine)

    require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script

    This is about require, but that is equivalent to require_once(). This is not a catchable error.

    By the way, you need to enter the absolute path, and I don't think this is right:

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

    You might want something like this

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

    Or, if you're calling this from a subdir or from a file that is included in different dirs, you might need something like

    require_once( '/var/www/yourPath/includes/functions.php' ); 
    
    0 讨论(0)
  • 2020-12-01 08:18

    This should work, but it is a bit of a hack.

    if(!@include_once("path/to/script.php")) {
        //Logic here
    }
    
    0 讨论(0)
提交回复
热议问题