Seeing the exit() PHP documentation got me thinking:
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");
Couple questions:
- What are common use cases besides opening files for using
exit()? - Since not every function everyone ever writes ends in
exit(), how do you know to use it in some contexts vs. others? - Are
if/elseandor/exitinterchangeable?
In that context, the
orin that statement is one of PHP’s logical operators which when used like that, will execute the second statement if and only if the first one fails due to short circuit evaluation.Since
fopenreturned false, theor exitstatement gets executed since the first part failed.To understand it better, here is a quick explanation of short-circuit evaluation.
In the above code, the expression
$y == 42is never evaluated because there is no need since the first expression was true.In that example, they are using the same logic for deciding whether or not to evaluate the statement that calls
exit.To address your questions:
exitcompletely depends on the code you are writing.or exitis just a bit shorter than usingif/else.Hope that helps.