PHP handle null handling by exception -



PHP handle null handling by exception -

is there way can tell php throw exception when trying access fellow member or method on null object?

e.g.:

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

right now, next errors not nice handle:

php notice: trying property of non-object in ... php warning: creating default object empty value in ... php fatal error: phone call undefined method stdclass::bar() in ...

i have specific exception beingness thrown instead. possible?

you can turn warnings exceptions using set_error_handler() when ever warning occurs, generate exception can grab in try-catch block.

fatal errors can't turned exceptions, designed php stop asap. can handle fetal error gracefully doing lastly min 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 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 phone call }catch(exception $ex){ echo "caught exception"; }

php exception nullpointerexception

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -