Section 22.3. Triggering Your Own Errors


22.3. Triggering Your Own Errors

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 programmersit 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 gray"it is just a string that is sent directly to users who find themselves on the receiving end of your error. The second parameter affects how the script should react to the error. If you do not provide the second parameter, the default is a user noticea 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 errorsit 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. That said, most people tend to write their own error-handling code, as it allows them more control over the content and stylekeep use of trigger_error( ) for errors that other programmers must fix when they use your code.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net