问题
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?
回答1:
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";
}
回答2:
Add this code in the file that is included or executed before anything else:
set_error_handler(
function($errno, $errstr, $errfile, $errline) {
throw new \ErrorException($errstr, $errno, 1, $errfile, $errline);
}
);
回答3:
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 should be executed or included before other code.
You can also implement a Singleton to avoid global variables or let it throw two exceptions, if you don't mind.
回答4:
The correct answer should be: NO. This is not possible in any PHP version.
来源:https://stackoverflow.com/questions/26204483/php-handle-null-handling-by-exception