Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture error on function "include" PHP?

i need capture the last error on function "include" PHP.

I test with the functions "Exceptions", but unfortunately i have written above the function "include".

If I write after the function "include" does not show the exception.

Example 1:

try{
        throw new exception();
        require_once( $this->controller['path'] );
    }
    catch( exception $e )
    {
        print_r( error_get_last() );
    }

This Return: ...(Void)...

Example 2:

try{

        require_once( $this->controller['path'] ) OR throw new exception();;
    }
    catch( exception $e )
    {
        print_r( error_get_last() );
    }

This return: Parse error: syntax error, unexpected T_THROW in...

I purposely created a syntax error in the file to include. The idea is to trap the error so that you can debug them.

Anyone have any idea how to get this?

Guys! I need to catch syntax errors. Greetings!

like image 765
Jorge Olaf Avatar asked Dec 06 '22 17:12

Jorge Olaf


1 Answers

First, if you use require, it's always going to kill your app if the file cannot be included. There's no control over the outcome, you cannot do anything afterwards. If you want to have control over the success of file inclusions, use include and test its return value.

$success = include "foo.php";
if (!$success) {
    // the file could not be included, oh noes!
}

You can have syntactical differences on that like:

if (!(include "foo.php")) ...

This will trigger an E_NOTICE if the file cannot be included, which you cannot catch. But that's OK, since it'll help you debug the issue and the display of errors will be turned off in production anyway (right, right?).

or throw new Exception doesn't work because throw is a statement and cannot be used where an expression is expected.


If you want to catch syntax errors in the included file, use php_check_syntax/it's successor php -l <file>.

like image 167
deceze Avatar answered Dec 10 '22 11:12

deceze