Triggering your own errors

void trigger_error ( string error_msg [, int error_type])

It is a fairly common task to want to bring up an error message similar to PHP's when your code is being used incorrectly, and this is what trigger_error() does. While it is not often necessary to throw up error messages in your code when only you use it, it becomes much more important when your code is being distributed to other programmers - it is often important to make sure they are using your code in the correct way, and to force output of a certain type of error if they are doing something unexpected.

The trigger_error() function takes two parameters: the string output message to be printed out as the error, and an optional second parameter of the type of error you want to issue. The first parameter can be whatever you wish, "Function X called with wrong parameter type", or "Objects of class MyElephant can only be grey" - it is just a string that is sent directly to users who find themselves on the receiving end of your error.

The second parameter, however, affects how the script should react to the error. If you do not provide the second parameter, the default is a user notice - a minor message that many people might not even see. However, you can select from any of the user error types as the second parameter, which can allow you to halt execution of the script if your error is triggered.

Using trigger_error() is better than just printing an error message and exiting the script because trigger_error() takes the form of PHP's default errors - it will automatically print out the filename and line number where the error occurred. Furthermore, it will uses PHP's default settings, which allow people to ignore certain classes of errors if they wish.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Source highlighting >>

Previous chapter: Making assertions

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.