Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I end my PHP script with exit or exit;? [duplicate]

Tags:

php

Today I have a little weird question.
Should I end my PHP script with exit or exit; and which is correct?.

Without ;

enter image description here

and

With ;

enter image description here

Thanks.


2 Answers

exit, exit;, exit(), and exit(); are exactly the same, but the fact is that you should not end your script with an exit() call, it's just bad practice (but it works).

EDIT

Clarifying why i said it's "bad practice", it's not about the functionality of "exit" itself, it's OK to halt the script execution if something bad happens, but the concept of "something bad" is really wide. In general, even if some unwanted condition occurs, the normal execution flow should reach to the end of the file. Just consider this example:

...some init stuff...
if (!user_is_authenticated) {
   ...print some nasty message...
   exit();
}
...continue with normal stuff...

A better approach would be:

...some init stuff...
if (user_is_authenticated) {
   ...continue with normal stuff...
}
else {
   ...print some nasty message...
}

What's the difference? The difference is that in the second version you don't need to use exit(), which means if one day you need to do something after BOTH the "normal" and "unwanted" execution flows you can just add it at the end of the file.

It's more or less the same argument about why you should NOT use "return" in function bodies except at the end of the function..

like image 170
Johnny Avatar answered Dec 06 '25 23:12

Johnny


It is allways a good practise to use semicolon

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>
like image 36
magic-sudo Avatar answered Dec 07 '25 01:12

magic-sudo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!