The exit(...)
and die(...)
statements should absolutely not be used in Web PHP pages as this might lead to a very bad
user experience. In such case, the end user might have the feeling that the web site is down or has encountered a fatal error.
But of course PHP can also be used to develop command line application and in such case use of exit(...)
or die(...)
statement can be justified but must remain limited and not spread all over the application. We expect exceptions to be used to handle errors and those
exceptions should be caught just before leaving the application to specify the exit code with help of exit(...)
or die(...)
statements.
Noncompliant code example
class Foo {
public function bar($param) {
if ($param === 42) {
exit(23);
}
}
}
Compliant solution
class Foo {
public function bar($param) {
if ($param === 42) {
throw new Exception('Value 42 is not expected.');
}
}
}