Let's work with an example like this:
try {
if( $var == false ) {
throw new Exception('Fail');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
Is there any way i can use $error
outside the catch block? If i try to print it outside,it shows nothing , so i'm sure i'm doing this wrong. Any help would be apreciated.
EDIT: This is my exact situation of the code click
I need to use $error , in another piece of code , outside of the class
This will return true if no error happens. Else it will return the error.
$error = false;
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
$error = $e->getMessage();
}
return $error;
It depends on your implementation whether to return true or false.
Actually you are returning the error message, if you remove the return false statement, and try to print outside the loop it will print.
you can do that in 2 way:
Option1:
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
$error = $e->getMessage();
// return false;
}
print_r($error);
Option 2:
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
return $error = $e->getMessage();
}
You should not The $error is declard inside the catch. You your function throws a Exception don't use try cactch. just throw the Exception
Your function should return just one type; If it returns boolean, return aways boolean
Maybe if you need to print the error, print it inside the catch