First thing we are going to do within our class, is set up the objects and the constructor. Like so:
<?php
class ErrorHandler
{
private $debug = 0;
public function __construct($debug = 0)
{
$this->debug = $debug;
set_error_handler(array($this, 'generalError'));
}
Lets break this down, first off since PHP 5 the keyword var has been deprecated and is replaced by one of the following 3: protected, private and public. You can look up more information on Google and PHP's website. We set the debug object to 0 (off) as a default, the next thing we do is make our constructor, in that we pass a parameter for the debug mode, then we tell PHP that we want our function “generalError” to handle all of PHP's errors.
Next thing that needs to be done is to create the “generalError” function:
public function handleError($type, $string, $file, $line)
{
switch ($type)
{
case FATAL:
switch ($this->debug)
{
case 0:
echo 'We have an error!';
exit;
case 1:
echo "<pre><b>FATAL</b> [T: $type] [L: $line] [F: $file]<br />$string<br /></pre>";
exit;
}
case ERROR:
echo "<pre><b>ERROR</b> [T: $type] [L: $line] [F: $file]<br/>$string<br /></pre>";
break;
case WARNING:
echo "<pre><b>WARNING</b> [T: $type] [L: $line] [F: $file]<br/>$string<br /></pre>";
break;
}
}
}
?>
Basically what we are doing here is receiving the four standard strings that PHP passes when it receives a warning or an error. Next thing we are doing is a switch statement to see what type of problem we are having, and if it is a fatal error we first see if we are in debug mode before we display the error because if we aren't in debug mode we only an to let the user see a little bit of information, if we are the testers need to know where to look.
Here is a little test file that you can use to test it:
<?php
require('ErrorHandler.php');
define('FATAL', E_USER_ERROR);
define('ERROR', E_USER_WARNING);
define('WARNING', E_USER_NOTICE);
$errorHandler = new ErrorHandler(1);
?>
Also if you want to trigger your own errors you would want to look up the trigger_error() funtion.
Finally the ways that you could improve this simple class is to create functions that would handle different problems, like database based errors, file errors etc.





MultiQuote




|