Answer the question
In order to leave comments, you need to log in
How to properly exit a PHP script?
Hello! There is a console application that takes some parameters as input and displays the result. If the parameter is entered incorrectly, then an error is intercepted, a custom message is displayed, and the script ends after die() / exit()
, since its further execution does not make sense.
The code is just for example:
class App
{
public static function checkEven ($number)
{
try {
if ($number % 2 !== 0) {
throw new Exception("Odd number");
}
return $number . ' even' . PHP_EOL;
} catch (Exception $error) {
print_r($error->getMessage() . PHP_EOL);
die(); // @codeCoverageIgnore
print_r("Too late");
}
}
}
print_r(App::checkEven(9));
// @codeCoverageIgnore
didn't help. die()
or should exceptions be handled differently? If so, how?
Answer the question
In order to leave comments, you need to log in
>Are there other ways to skip execution of die() or should exceptions be handled differently? If so, how?
replace die with return and swap it with print_r. You don't really need to forcibly terminate php - as soon as the code is executed, the request processing will complete itself.
If you are afraid that some action will be performed somewhere below the code, which should be performed only in case of successful completion, add an additional condition there that will check the result, or catch the exception there, and leave the catch empty. And all will be well.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question