Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - exit or return which is better?

Tags:

php

terminate

People also ask

Should you use exit in PHP?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.

Does return exit the function PHP?

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.

Why do we use return in PHP?

The return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running.


Since you are using exit and return within the global scope (not inside a function), then the behavior is almost the same.

The difference in this case will appear if your file is called through include() or require(). exit will terminate the program, while return will take the control back to the calling script (where include or require was called).


I would tend to go with the return() method, so that other scripts can continue executing. That way, if you ever use another script to call this one, it can do error-handling to deal with the case where the file is too large, as opposed to always halting execution.


It depends...if your script is intended to do nothing else but output a message, and you don't want the script to do anything afterwards, exit() will work. Otherwise, use return.


Exit terminates the program like die(). manual