php_nub_qq
php_nub_qq

Reputation: 16015

set_exception_handler() not catching exceptions

I am building the basics of my error reporting system, basically I have these two bad boys set up

class System {
    public function __construct(){
        set_exception_handler(array($this, 'handleExceptions'));
        set_error_handler(array($this, 'handleGenericError'));
    }

    public function handleExceptions(\Exception $e){
        echo "<pre>".print_r($e, true)."</pre>";
    }

    public function handleGenericError($no, $msg, $file, $line, $context){
        $msg .= ' in ['.$file.'] on line ['.$line.']';
        throw new \Exception($msg);
    }
}

Then I provoke an error in the __construct method, after the declarations. Statements like

public function __construct(){
    ....
    echo $undefined_variable;
}

And

public function __construct(){
    ....
    echo $this->undefined_variable;
}

Seem to go well, printing a nice readable exception message, but if I do this

public function __construct(){
    ....
    echo $this->$undefined_variable;
}

I get an uncaught exception. Why is that? The exception being thrown is from the handleGenericError method, I can tell because it has [] around it and stuff. This is a little confusing. :/

Upvotes: 1

Views: 348

Answers (1)

Giacomo1968
Giacomo1968

Reputation: 26066

The problem—as I see it—is this:

public function __construct(){
    ....
    echo $this->$undefined_variable;
}

Will most likely result in:

echo $this->[null];

When you do assignment like $this->$undefined_variable I believe PHP parses that as “Assign the value of the variable $undefined_variable to the are it is placed in right after $this->.” Meaning it’s not even getting to the handler because 100% of nothing is there. It’s simply a null value. It is as if you called:

echo $this->;

Which is a larger program logic failure because all an exception handler does is catch errors that successfully get to it. A call to $this-> is a fundamental logic failure outside of the scope of the class & the exception handler within it. You can read up on how exception handlers in PHP work here.

Upvotes: 1

Related Questions