114Part IPHP: The BasicsThe custom function print_header()is designed to make it easy for us to place a standard- ized, search engine friendly header at the top of each page. However, we ve left the descrip- tion variable undefined, which will not yield an error, but will leave us without a meaningfuldescription for our page. Unfortunately, because the function is essentially called correctlyand PHP is forgiving in nature, we may never know that we ve left off this important detail. Some form of error handling is necessary to point this out, and Exceptionsprovide a handyway of dong so. Consider this revised code: function print_header($title, $keywords, $description) { if(strlen($description) < 40) throw new Exception( A reasonable description length isrequired
); print(
); print(
$title ); print(
); print(
); print( ); } try { print_header( My Page , PHP, Programming, Beer , ); } catch (Exception $e) { echo($e->getMessage()); } The first new thing in our revised function is a simple test in line 2 suggesting an appropriateminimum length for the $descriptionvariable. The line immediately following initiates aninstance of the Exceptionclass with the message suggested by the quoted value. A class is one of the recent OOP concepts introduced in PHP4. You can create your own classesand extensions of existing classes, including those for Exception handling. PHP gives youException for free. We ll go into much greater depth on the subject of classes in Chapter 20 andexception handling itself in Chapter 31. Next, instead of simply calling our function, we ve enclosed the function in a new controlstructure, the try…catchblock. If we execute the code as written, PHP first tries to exe- cute the function as described; then it terminates execution almost immediately, because the$descriptionvariable has failed our simple test. At this point, the script can continue exe- cution after the try…catchblock, or it can be terminated with die()or exit(). Multiple exceptions can be defined in a single function. This is good idea because it yieldsmore specific information about what exactly happened. Because execution stops with thefirst exception, only this exception will be caught. Exceptions are a huge topic; they re outlined here so you can start using them immediately. You ll find nods to Exceptions throughout this book, but they are covered in depth in Chapter 31. Cross- ReferenceNote08
Check
Tomcat Web Hosting services for best quality webspace to host your web application.
This entry was posted
on Sunday, August 19th, 2007 at 8:22 pm and is filed under MYSQL5.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.