PHP processing exception fixed

Is there a way that PHP can throw an exception when I try to access an element or method of a null object?

eg:.

 $x = null; $x->foo = 5; // Null field access $x->bar(); // Null method call 

Currently, I am getting only the following errors that are not suitable for processing:

 PHP Notice: Trying to get property of non-object in ... PHP Warning: Creating default object from empty value in ... PHP Fatal error: Call to undefined method stdClass::bar() in ... 

I would like a specific exception to be thrown instead. Is it possible?

+6
source share
4 answers

You can turn your warnings into exceptions using set_error_handler () , so when a warning ever comes up, it throws an exception that you can catch in a try-catch block.

Fatal error cannot be turned into Exceptions, they are intended for php to stop as soon as possible. however, we can handle the fetal error gracefully by doing the last minute processing using register_shutdown_function ()

 <?php //Gracefully handle fatal errors register_shutdown_function(function(){ $error = error_get_last(); if( $error !== NULL) { echo 'Fatel Error'; } }); //Turn errors into exceptions set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }); try{ $x = null; $x->foo = 5; // Null field access $x->bar(); // Null method call }catch(Exception $ex){ echo "Caught exception"; } 
+2
source

Add this code to the file that is included or executed first:

 set_error_handler( function($errno, $errstr, $errfile, $errline) { throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); } ); 
+1
source

Try this code to catch all errors:

 <?php $_caughtError = false; register_shutdown_function( // handle fatal errors function() { global $_caughtError; $error = error_get_last(); if( !$_caughtError && $error ) { throw new \ErrorException($error['message'], $error['type'], 2, $error['file'], $error['line']); } } ); set_error_handler( function($errno, $errstr, $errfile, $errline) { global $_caughtError; $_caughtError = true; throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); } ); 

It must be executed or included before other code.

You can also implement Singleton to avoid global variables or let it throw two exceptions if you don't mind.

+1
source

The correct answer should be: NO. This is not possible in any version of PHP.

0
source

Source: https://habr.com/ru/post/1204051/


All Articles