Article

PHP5: Coming Soon to a Webserver Near You

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Next

By defining your own Exception subclasses, you can also define multiple catch{} blocks, allowing you to respond to different types of errors in different ways. The following example should make this a little clearer:

           
<?php            
class ValueError extends Exception {            
   function __construct($message) {            
       parent::Exception($message);            
   }            
}            
           
class TypeError extends Exception {            
   function __construct($message) {            
       parent::Exception($message);            
   }            
}            
           
function getForm($error=false) {            
   $form=<<<EOD            
<form action="{$_SERVER['PHP_SELF']}" method="POST">            
<input type="text" name="firstName"><br />            
<input type="submit" name="submit" value="Send">            
</form>            
EOD;            
   if ( $error ) {            
       $form.="<br>\n<b>".$error."</b>\n";            
   }            
   return $form;            
}            
           
if ( isset ( $_POST['submit'] ) ) {            
   try {            
       if ( empty($_POST['firstName']) ) {            
           throw new ValueError('Please enter your name(!)');            
       } else if ( preg_match("/[^A-z$]/",$_POST['firstName']) ) {            
           throw new TypeError('You must enter a string value');            
       } else {            
           echo ( 'Hello '.$_POST['firstName'] );            
       }            
   } catch ( ValueError $e ) {            
       echo ( getForm($e->getMessage()) );            
   } catch ( TypeError $e ) {            
       echo ( 'You have been banned from this site!' );            
   }            
} else {            
   echo ( getForm() );            
}            
?>            

Script: exception4.php

Notice how the two catch{} blocks "listen" for different exceptions?

When the form is submitted, if the user forgot to enter their name, a ValueError is thrown and a polite message is displayed to remind the user to complete the form field.

Meanwhile, (taking a somewhat extreme view) if the user does fill in the name field, but enters a character that’s not a letter of the alphabet, they are banned from the site (in practice, the site then ignores further requests from their IP address), the assumption being that they tried an SQL injection attack or some other dodgy maneuver.

It's also possible to take some control over errors which would normally generate PHP errors. For example:

           
<?php            
class IOError extends Exception {            
   function __construct($message) {            
       parent::Exception($message);            
   }            
}            
           
class FileReader {            
   private $resource;            
   function __construct($filename) {            
       if ( ! $this->resource = @fopen($filename,'r') )            
           throw new IOError('Unable to open '.$filename);            
   }            
   function read() {            
       if ( !feof($this->resource) )            
           return fgets($this->resource);            
       else            
           return false;            
   }            
   function __destruct() {            
       fclose($this->resource);            
   }            
}            
           
try {            
   $fileReader = new FileReader('doesnotexist.txt');            
   while ( $content = $fileReader->read() ) {            
       echo ( $content );            
   }            
} catch ( IOError $e ) {            
   echo ( $e->getMessage() );            
}            
?>            

Script: exception5.php

Here I've suppressed the PHP error message that would occur when fopen() attempted to open an non-existent file; this allows me to handle it in my code as an Exception.

Note that with the current Beta, it's unclear (at least to me) to what degree Exception handling can be used in conjunction with native PHP errors. Certainly it would be nice to be able to "map" some PHP error codes to Exceptions for situations like type hinting (which I looked at above), so that when a PHP error occurs, it causes an exception to be thrown, rather than generating a PHP error. To some degree, it may be possible to work around this using PHP4-style custom error handlers.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links