Reputation: 1936
I want to get an errors object from a callback function. here is what i have done so far.
$errors = null;
set_exception_handler(function($exception) use (&$errors) {
$errors = $exception;
var_dump($exception); // works fine
});
var_dump($errors); // give null ????
throw new Exception("blablblablablabla", 0);
I am sure with an anonymous function and a variable would work very fine ! But in this case with a callback and object I am not sure what's going on ? i can't get my head a round. any help explanation would be really appreciated.
Upvotes: 1
Views: 280
Reputation: 2505
You are assigning the anonymous function as an exception handler with set_exception_handler()
.
Yet you do not throw an exception in your code. Therefore the anonymous function is never called, because there was no event to handle, which means that $error
was never set.
If you add a try catch
block your function will also not be called. This can be seen by the fact, that the line var_dump($exception)
from within your handler is not called either.
If you want to store the last called exception in your code, you may need to use a wrapper function around that code, that uses try catch
to overwrite a static resource with the last exception encountered.
Note, that the exception within the given function is never fully thrown, because it was catched by the wrapper!
class Catcher {
private static $_EXCEPTION = null;
public static function GET_EXCEPTION () {
return self::$_EXCEPTION;
}
public static function run($func) {
try {
return $func();
} catch (Exception $e) {
self::$_EXCEPTION = $e;
}
}
}
var_dump(Catcher::GET_EXCEPTION()); //dumps NULL
Catcher::run(function(){
throw new Exception('I was called');
});
var_dump(Catcher::GET_EXCEPTION()); //dumps the last thrown exception
Upvotes: 1
Reputation: 41810
set_exception_handler
does not stop execution. It just defines what will happen if/when an exception occurs, so you can var_dump($errors);
errors after setting it. $errors
will still be null at that point because you have set it to null, and nothing has happened yet to change that.
The thing that does stop execution is when an exception actually occurs and the anonymous function defined in set_exception_handler
is called. At that point, the var_dump($exception);
within that function is called, but any other code in the main program after the point where the exception occurred will not be executed.
Storing the exception in a global variable from within the exception handler doesn't make really sense, because if the exception handler is called, no more code in the main program will be executed, so you won't be able to use that variable anyway.
Upvotes: 2