3

I am trying to write an error handler class for php. I've tested that the object has been created but it doesn't seem to be handling errors.

I used the same code in a function in the index file initially and it worked fine, but I'd rather have a class. Why is this not handling errors?

class class_error
{
    public function __construct()
    {
        // set to the user defined error handler
        set_error_handler($this->errorHandler());
    }

    public function errorHandler($errno, $errstr, $errfile, $errline)
    {
        //don't display error if no error number
        if (!(error_reporting() & $errno)) {
            return;
        }

        //display errors according to the error number
        switch ($errno)
        {
            case E_USER_ERROR:
                echo "<b>ERROR</b> [$errno] $errstr<br />\n";
                echo "  Fatal error on line $errline in file $errfile";
                echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
                echo "Aborting...<br />\n";
                exit(1);
                break;

            case E_USER_WARNING:
                echo "<b>WARNING</b> [$errno] $errstr<br />\n";
                break;

            case E_USER_NOTICE:
                echo "<b>NOTICE</b> [$errno] $errstr<br />\n";
                break;

            default:
                echo "<b>UNKNOWN ERROR</b> [$errno] $errstr<br />\n";
                break;
        }

        //don't execute PHP internal error handler
        return true;
    }
}
2
  • 1
    Added it as an answer. Commented Nov 4, 2013 at 16:51
  • yep ill give u a tick in a few ticks :) Commented Nov 4, 2013 at 16:52

1 Answer 1

5

Use this:

set_error_handler(array($this, "errorHandler"));

More info: http://php.net/manual/en/language.types.callable.php

Sign up to request clarification or add additional context in comments.

2 Comments

If your PHP is up to date, use short array syntax: set_error_handler([$this, 'errorHandler']).
Did not even know that this exists. Thanks for sharing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.