I am calling it.  The death of the PHP die function.  Now, I have no actual authority to do so.  My PHP CVS karma does not extend that far.  And I doubt it will actually get removed despite it being nothing more than an alias for exit now.

No, what I would like to call a death to is the usage of die such as:

$conn = mysql_connect($server, $user, $pass) or die("Could not connect to MySQL, but needed to tell the whole world");
I don't know who thought that particular usage was good, but they need to .... no, that is harsh.  I just really wish they had never done that.

So, what should you use?  Well, there are a couple of options depending on what context you are working in and whether or not the failure is actually catastrophic.


If you are using OOP in your PHP code, Exceptions are the logic choice for dealing with errors.  I have mixed feelings about them.  But, it has more to do with the catching of exceptions than the throwing of them.  If you are going to live in a world of exceptions, please catch them and provide useful error messages.  The PHP world is not too bad about that, but I have read too many Java error logs full of huge, verbose exception dumps in my life already.  Please don't follow that technique in PHP.


The function trigger_error is quite handy.  It allows you, a common PHP coder, to create errors just like the core system.  So, the error messages are familiar to anyone that is used to seeing PHP errors.  So, if your system is configured to log errors and not display them, errors from trigger_error will be treated the same as built in errors.

Also, errors thrown with trigger_error are caught by a custom error handler just like built in errors.  They can be logged, printed, whatever you want from that error handler, just like normal PHP errors.  There are even several levels of errors you can raise like notices, warnings, errors, and even deprecated.  Again, just like the built in PHP errors.

FATAL Errors

trigger_error is also the most suitable way, IMO, to end a script immediately.

$conn = mysql_connect($server, $user, $pass);
if(!$conn) {
    trigger_error("Could not connect to MySQL database.", E_USER_ERROR);

Now that will not be told to the whole world if you have display_errors set to Off as you should in any production environment.