Is there a way I can tell PHP to throw an exception when I am trying to access a member or method on a null
object?
E.g.:
$x = null;
$x->foo = 5; // Null field access
$x->bar(); // Null method call
Right now, I only get the following errors which are not nice to handle:
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 to have a specific exception being thrown instead. Is this possible?
The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.
When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.
You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.
Since PHP7 you can catch fatal errors, example below:
$x = null;
try {
$x->method();
} catch (\Throwable $e) {
throw new \Exception('$x is null');
}
You can turn your warnings into exceptions using set_error_handler() so when ever an warning occurs, it will generate an Exception which you can catch in a try-catch block.
Fatal errors can't be turned into Exceptions, they are designed for php to stop asap. however we can handle the fetal error gracefully by doing some 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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With